简体   繁体   English

jQuery类选择器并单击()

[英]jQuery class selector and click()

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) 有效的jsFiddle示例 (加载了jQuery 1.5)
HTML (in case jsFiddle is inaccessible): HTML(如果jsFiddle无法访问):

<!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: 使用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. Safari的Inspector表明正在正确加载jQuery,所以这不是问题。 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() 您需要将代码包装在$(document).ready()中

This will work 这会奏效

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

JSfiddle does this for you automatically JSfiddle会自动为您完成此操作

Wrap the code inside 将代码包装在里面

$(function (){

})

And you have the working code 而且你有工作代码

$(function (){

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

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM