快疯了。使用 jquery 检查复选框时的简单警报
单击/选中复选框时,我无法收到简单的警报。我一直在挠头,想知道为什么我无法让它工作,而且我知道这将是一件简单的事情......那么,我做错了什么?
<script type="text/javascript">
$('#test1').click(function(){
alert('clicked');
});
</script>
<input type="checkbox" id="test1" value="test1" name="test1" value="-1">test1</input>
I cannot get a simple alert to fire when a checkbox is clicked/checked. I have been scratching my head wondering why I cant get it to work and I know it is going to be something simple... So, what am I doing wrong?
<script type="text/javascript">
$('#test1').click(function(){
alert('clicked');
});
</script>
<input type="checkbox" id="test1" value="test1" name="test1" value="-1">test1</input>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不是在等待 DOM 准备就绪。如果你愿意,它会起作用:
小提琴: http://jsfiddle.net/sanbc/
You are not waiting for DOM ready. If you will, it'll work:
Fiddle: http://jsfiddle.net/sanbc/
您需要将其包装在 document.ready() 中,否则可能会在元素存在之前分配单击事件。
或者
确保包含 jQuery 库。
或者
确保不包含其他 javascript 库,它们可能会弄乱 $ 对象。如果是,请将 $ 替换为 jQuery。
尝试一下,然后回复我并发表评论
You'll want to wrap it in document.ready() otherwise the click event might be assigned before the element exists.
OR
Make sure the jQuery library is included.
OR
Make sure no other javascript libraries are included, they can mess up the $ object. If they are, replace $ with jQuery.
Try those and get back to me with a comment
这对我有用。
示例: http://jsfiddle.net/jasongennaro/9dSMM/
也许 DOM 有问题还没准备好?
请记住将其包装在
document.ready
中。更多信息
This works for me.
Example: http://jsfiddle.net/jasongennaro/9dSMM/
Perhaps there is a problem with the DOM not being ready?
Remember to wrap this in a
document.ready
.More here
将代码放入
$(document).ready
事件中,以便在尝试向其注册事件处理程序时确保该复选框存在。Put your code inside a
$(document).ready
event so that you can be sure the checkbox exists when you try to register an event handler with it.只是为了检查明显的情况,如果没有这个包装器,我从未编写过任何 Jquery UI 代码:
Just to check the obvious, I've never written any Jquery UI code without this wrapper: