简体   繁体   English

jQuery不能正常工作

[英]jQuery just not working

For some reason my jQuery script just doesn't want to work, and it's really really simple, I've taken everything away except the actual jquery script, it's really annoying please help. 由于某种原因,我的jQuery脚本只是不想工作,而且确实非常简单,除了实际的jQuery脚本之外,我已经删除了所有内容,确实很烦人,请帮忙。 Thank you! 谢谢!

 <!doctype html>
<html>

    <head>
        <script src="jquery.js"></script>
        <script>
            $("#click").click(function () {
                alert("works!");
            });
        </script>
    </head>

    <body>
        <a href="#" id="click">Button</a>
    </body>

</html>

PS jQuery JS file is valid. PS jQuery JS文件有效。

Change your code to this. 将代码更改为此。 It ensures that the JavaScript is executed once all your HTML elements have been loaded to the page: 它确保将所有HTML元素加载到页面后执行JavaScript:

$(document).ready(function () {
   $("#click").click(function() {
      alert("works!");
   });
});

However, you should move your script tags to the bottom of the page , to ensure that they do not block. 但是, 您应该将脚本标记移到页面底部 ,以确保它们不会被阻塞。 This will also mean you don't actually need the $(document).ready callback. 这也意味着您实际上不需要$(document).ready回调。

You need to wrap your code within 您需要将代码包装在其中

$(function(){
    // your code here which relies on DOM elements
});

Otherwise you DOM has not been loaded and events will not be bound to elements. 否则,您的DOM尚未加载,并且事件将不会绑定到元素。

Wrap your functions into the $(document).ready() 将您的函数包装到$(document).ready()

$(document).ready(function(){
    $("#click").click(function() {
        alert("works!");
    });
});

Add your code inside document.ready like this 将您的代码添加到document.ready

$(document).ready(function () {
  $("#click").click(function () {
       alert("works!");
   });
});

or add your code at the end of the document like this 或像这样在文档末尾添加代码

<body>
   <a href="#" id="click">Button</a>
   // Other elements...
    <script type="text/javascript">
            $("#click").click(function () {
                alert("works!");
            });
    </script>
</body>
$(document).ready(function(e) {
//TO DO  your code goes here         
}); 

Just change your script tag to the "/body" tag. 只需将脚本标签更改为“ / body”标签即可。 That will let the browser create the DOM and read script's one by one! 这将使浏览器创建DOM并逐一读取脚本! Cheers! 干杯!

Try this: 尝试这个:

$("#click").live("click",function() {
    alert("works!");
});

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

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