Why is this jQuery click function not working?(为什么这个 jQuery 点击功能不起作用?)
问题描述
代码:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
</script>
上面的代码不起作用.当我单击#clicker 时,它不会发出警报,也不会隐藏.我检查了控制台,没有收到任何错误.我还检查了 JQuery 是否正在加载,确实如此.所以不确定是什么问题.我还做了一个带有警报的文档准备功能,并且该功能有效,因此不确定我做错了什么.请帮忙.谢谢!
The above code doesn't work. When I click on #clicker, it doesn't alert and and it doesn't hide. I checked the console and I get no errors. I also checked to see if JQuery was loading and indeed it is. So not sure what the issue is. I also did a document ready function with an alert and that worked so not sure what I am doing wrong. Please help. Thanks!
推荐答案
您应该在 $(document).ready(function() {});
块中添加 javascript 代码.
You are supposed to add the javascript code in a $(document).ready(function() {});
block.
即
$(document).ready(function() {
$("#clicker").click(function () {
alert("Hello!");
$(".hide_div").hide();
});
});
正如 jQuery 文档 所述:在文档准备好"之前,无法安全地操作页面.jQuery 会为您检测到这种准备状态.包含在 $( document ).ready()
中的代码只会在页面运行一次文档对象模型 (DOM) 已准备好执行 JavaScript 代码"
As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"
这篇关于为什么这个 jQuery 点击功能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!