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 点击功能不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么这个 jQuery 点击功能不起作用?


基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01