Javascript jQuery 类选择器和 click()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5125621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery class selector and click()
提问by Anonymous
I'm currently trying to get an alert to happen when something is clicked. I can get it working in jsFiddle, but not in production code:
我目前正在尝试在单击某些内容时发出警报。我可以让它在 jsFiddle 中工作,但不能在生产代码中工作:
jsFiddle example that works(jQuery 1.5 loaded)
HTML (in case jsFiddle is inaccessible):
有效的 jsFiddle 示例(加载了 jQuery 1.5)
HTML(以防 jsFiddle 无法访问):
<!DOCTYPE HTML><html><head><title>Test</title></head>
<body> <h1>25 Feb 2011</h1><h3>ABC</h3><ul>
<li class="todoitem">Test—5 minutes</li> </ul>
</body></html>
Javascript:
Javascript:
$(".todoitem").click(function() {
alert('Item selected');
});
Non-working production example:
非工作生产示例:
<!DOCTYPE HTML><html><head><title>Test</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(".todoitem").click(function() {
alert('Item selected');
});
</script>
</head>
<body>
<h1>25 Feb 2011</h1><h3>ABC</h3><ul><li class="todoitem">Test—5 minutes</li></ul>
</body>
</html>
Safari's Inspector indicate that jQuery is being loaded correctly, so that's not the issue. As far as I can tell, these two pieces of code are essentially identical, but the latter isn't working. Can anyone see what I've done wrong?
Safari 的 Inspector 表明 jQuery 被正确加载,所以这不是问题。据我所知,这两段代码本质上是相同的,但后者不起作用。谁能看到我做错了什么?
回答by JohnP
You need to wrap your code in $(document).ready()
您需要将代码包装在 $(document).ready() 中
This will work
这将工作
$(document).ready(function(){
$(".todoitem").click(function() {
alert('Item selected');
});
});
JSfiddle does this for you automatically
JSfiddle 自动为你做这件事
回答by Santosh Linkha
Wrap the code inside
将代码包裹在里面
$(function (){
})
And you have the working code
你有工作代码
$(function (){
$(".todoitem").click(function() {
alert('Item selected');
});
})