jQuery添加到JSP页面

8

我有一段在网上找到的jQuery代码,我想将其集成到我的jsp页面中,我使用Spring表单标签。

这是jQuery代码:

(function ($) {
    //тут превращаем select в input    
    var id = "test",
        $id = $('#' + id),
        choices = $id.find('option').map(function (n, e) {
            var $e = $(e);
            return {
                id: $e.val(),
                text: $e.text()
            };
        }),
        width = $id.width(),
        realClass = $id.get(0).className,
        realId = $id.get(0).id,


        $input = $('<input>',{width: width});
    $id.after($input);
    $id.hide();
    $id.find('option').remove();
    //превратили

    $input.select2({
        query: function (query) {
            var data = {}, i;
            data.results = [];

            // подтставим то что искали

            if (query.term !== "") {
                data.results.push({
                    id: query.term,
                    text: query.term
                });
            }

            // добавим остальное

            for (i = 0; i < choices.length; i++) {
                if (choices[i].text.match(query.term) || choices[i].id.match(query.term)) data.results.push(choices[i]);
            }

            query.callback(data);
        }
    }).on('change',function()
          {   
              var value=$input.val();
              $id.empty();
              $id.append($('<option>').val(value))
              $id.val(value);             
          }
         );
})(jQuery);

jQuery的CSS文件 - 我将其命名为test.css并应用于我的JSP页面:

#test {
    width: 300px;
}

我的JSP页面

 <html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<title>Страница выборки</title>
<link rel="stylesheet" href="resources/cssFiles/jquery-ui.css"/>
<link rel="stylesheet" href="resources/cssFiles/test.css"/>
<script type="text/javascript" src="resources/jsFiles/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="resources/jsFiles/jquery-ui.js"></script>
<script type="text/javascript" src="resources/jsFiles/jquery-ui-i18n.js"></script>
<script type="text/javascript" src="./resources/jsFiles/selecter.js"></script>
<script type="text/javascript">

 $(document).ready(function()
         {

         $("#parctdate, #chldAdmitDate, #chldSchlDate, #name, #type, #daySchdl, #workSchdl, #rotation, #numbch, #chUnder3, #chUpper3, #chGoSchool, #chAdmitted").mouseenter(function() {        
             $(this).css("background-color", "gainsboro");   
         });

         $("#parctdate, #chldAdmitDate, #chldSchlDate, #name, #type, #daySchdl, #workSchdl, #rotation, #numbch, #chUnder3, #chUpper3, #chGoSchool, #chAdmitted").mouseleave(function() {        
             $(this).css("background-color", "white");   
         });

         var enabledDays = ["6-1-2013", "7-1-2013", "8-1-2013", "9-1-2013", "10-1-2013", "11-1-2013"];
         function nationalDays(date) {
                var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();            
                for (i = 0; i < enabledDays.length; i++) {
                    if($.inArray((m+1) + '-' + d + '-' + y,enabledDays) != -1 || new Date() > date) {           
                        return [true];
                    }
                }
                return [false];
            }

         $(function(){
               $.datepicker.setDefaults($.extend($.datepicker.regional["ru"]));
               $("#datepicker1, #datepicker2, #datepicker3").datepicker({dateFormat: "yy-mm-dd",
                                                                         duration: "normal",
                                                                         numberOfMonths: [ 1, 2 ],
                                                                         constrainInput: true,
                                                                         beforeShowDay: nationalDays});   
             });         


     });

</script>

</head>

<body>

<spring:message code="label.input.button" var="labelbutton"/>

<h3 align="center"><spring:message code="label.input.topLabel"/></h3>


<form:form  id="myform" cssClass="testClass" modelAttribute="fboAttribute" method="post" action="add" >
<table align="center">  


<tr id="name">
<td><form:label path="institution.nameOfInstitution"><spring:message code="label.input.nameOfInstitution"/></form:label>
<form:select id="test"  path="institution.nameOfInstitution"> 
<form:option  value=""><spring:message code="label.select.msg" />-</form:option>
<form:options items="${listOfInstitutionsNames}"/>
</form:select> 

<tr>
<td><input type="submit" value="${labelbutton}"/></td>

</table> 
</form:form>

我希望能将我的 jQuery 脚本与 jsp 和 Spring 表单标签集成起来。
很抱歉我对 jQuery 还很陌生。
谢谢。

你好,集成的意思是什么? - Akheloes
@java_user:你知道如何将jQuery添加到普通的HTML页面中吗?如果是这样,那么在JSP和HTML中执行此操作之间没有太大区别。事实上,jQuery就像任何JS(JavaScript)一样,您可以在HTML中的任何标签中使用它(无论是Spring还是其他)。 - Akheloes
所以你想要真的移除Spring表单标签? - Akheloes
@Gloserio 是的先生,我想要去掉Spring表单标签。 - java_user
好的。但是,从我看到的内容来看,您所谓的“jQuery示例_html”和Spring表单标签之间的区别仅在于类属性,我错了吗? - Akheloes
显示剩余6条评论
3个回答

4

jQuery和任何JavaScript一样,都需要在JSP页面的<head>标签中的<script>标签中添加。您可以添加全部代码或者只是链接到包含jQuery代码的.js文件,例如:

<script src="./libs/jquery/1.10.1/jquery.min.js"></script>

完成以上步骤后,您现在想要在HTML标签中利用jQuery,与任何HTML页面一样操作。在您的情况下,不需要删除Spring标签,让它通过${listOfInstitutionsNames}生成select/options,只需在Spring表单标签中加上class="testclass"即可,像这样:
<form:form  cssClass="testclass" id="myform" modelAttribute="fboAttribute" method="post" action="add" >

渲染表单时,Spring会在生成的HTML中包含class属性,其值为testclass。希望这能帮到你,祝你好运。

谢谢您的回答...我按照您说的做了,但还是不行。哦,我在Spring表单中没有类,而是有cssClass。我已经编辑了我的问题,供您参考。 - java_user
jquery.min.js文件中包含什么?这是一个标准文件吗?我们需要将其放入我们的Web项目中,在<script type="text/javascript"> </script>下使用jQuery函数吗? - Suresh

1
如果您的意思是想将Java侧的信息绑定到JS var,您可以按照我所做的步骤来进行:
1. 在Java端,使用Google的Gson将Java对象编码为Json字符串。 2. 在Java端,使用org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(String)将Json字符串转义为JavaScript字符串。 3. 在JSP端,执行类似于以下的操作:
    <script>
    var jsonObject = JSON.parse("<%=yourJsonString%>");
    </script>

1

对于使用MVC模型设计的动态Web项目:

在头部区域添加如下内容:

<script type="text/javascript" src="${pageContext.request.contextPath}/jQuery.js"/></script>

我将我的jQuery.js文件放在WebContent文件夹中(与jsp页面一起)。

jQuery.js 文件里面有什么内容?这是一个标准文件吗,我们需要将其放入我们的 Web 项目中,在 <script type="text/javascript"> </script> 下使用 jQuery 函数吗? - Suresh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接