简体   繁体   English

jQuery在Struts2的JSP中不起作用

[英]JQuery is not working in JSP with Struts2

I have included the JQuery CDN in the <script> tag,but it does not works. 我在<script>标记中包含了JQuery CDN,但是它不起作用。 I am using intellij, it prompts me WITH such warning "Unresolved function or method $()" 我正在使用intellij,它以这样的警告提示我:“未解析的函数或方法$()”

Any response is appreciated 任何回应表示赞赏

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
    <script src="http//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
    <title>Success</title>
    <script>
        $("#select").click(function() {
            alert("aaaa");
        });
        $("#delete").click(function() {
            alert("aa");
        });

    </script>
</head>
<body>
<label for="person">personname</label>
<input id="person" name = "person" type="text" />
<input id="add"type="button" value="add" />
<input id="delete"type="button" value="delete"/>
<input id="select"type="button" value="select"/>
<input id="update"type="button" value="update"/>


</body>
</html>

Since you have put all js inside header you have to put it inside document.ready . 由于您已将所有js放在标头中,因此必须将其放在document.ready

<script>
$(document).ready(function(){
 $("#select").click(function() {
            alert("aaaa");
        });
        $("#delete").click(function() {
            alert("aa");
        });

})
</script>

This is because script tag is a blocking tag and when you put it inside header tag, it will be parsed before DOM is ready. 这是因为script标记是一个阻止标记,当您将其放入标头标记中时,将在DOM准备就绪之前对其进行解析。 At that time jQuery don't know what is #select & #delete , so no way it will able to attach the click handler. 那时jQuery不知道什么是#select#delete ,因此它无法附加click处理程序。

A second option is to put all script near closing body tag. 第二种选择是将所有脚本放在结束body标签附近。 So first DOM will be ready with elements then js will be executed. 因此,首先DOM将准备好包含元素,然后将执行js。 Then you can remove the 然后,您可以删除

$(document).ready(function(){
})

Example

<body>
    <!--All HTML elements-->
    <script>
        // All your js goes here.
    </script>

There are several advantage of putting scripts just before closing </body> tag , which is beyond this question 将脚本放在</body>标签之前,有很多好处,这超出了这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM