简体   繁体   中英

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 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

Wrap the code inside

$(function (){

})

And you have the working code

$(function (){

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

})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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