jQuery类选择器并单击() [英] jQuery class selector and click()

查看:121
本文介绍了jQuery类选择器并单击()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正尝试在点击某件事物时发出警报。我可以让它在jsFiddle中工作,但不能用在生产代码中:

jsFiddle工程示例(jQuery 1.5加载)

HTML(如果jsFiddle无法访问):

 <!DOCTYPE HTML>< html>< head>< title> Test< / title>< / head> 
< body> < h1> 2011年2月25日< / h1>< h3> ABC< / h3>< ul>
< li class =todoitem>测试& mdash; 5分钟< / li> < / UL>
< / body>< / html>

Javascript:

  $(。todoitem)。click(function(){
alert('Item selected');
});

非工作生产示例:

 <!DOCTYPE HTML>< html>< head>< title> Test< / title> 
< script src =http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.jstype =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>测试& mdash; 5分钟< / li>< / UL>
< / body>
< / html>

Safari的Inspector表明jQuery被正确加载,所以这不是问题。据我所知,这两段代码基本相同,但后者不起作用。任何人都可以看到我做错了什么?

解决方案

您需要将代码包装在$(document).ready()



这将起作用

  $(document).ready(function (){
$(。todoitem)。click(function(){
alert('Item selected');
});
});

JSfiddle会自动为您做这件事


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 example that works (jQuery 1.5 loaded)
HTML (in case jsFiddle is inaccessible):

<!DOCTYPE HTML><html><head><title>Test</title></head>
<body> <h1>25 Feb 2011</h1><h3>ABC</h3><ul>
        <li class="todoitem">Test&mdash;5 minutes</li> </ul>
</body></html>

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&mdash;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?

解决方案

You need to wrap your code in $(document).ready()

This will work

$(document).ready(function(){
        $(".todoitem").click(function() {
            alert('Item selected');
        });
});

JSfiddle does this for you automatically

这篇关于jQuery类选择器并单击()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆