SNSD
SNSD

Reputation: 23

Why my click not work as expected?

I just try this code:

$("#test").ready(function() {
    $(this).click(function() {
        alert('clicked!');
    });
});

Fiddle here: http://jsfiddle.net/8bfqw/

Why it's still alert when I click outside of the div?

Upvotes: 2

Views: 97

Answers (3)

Eli
Eli

Reputation: 14827

It's because your selector $(#test) is actually $(document) since from the docs:

The .ready() method can only be called on a jQuery object matching the current document

Whatever you pass inside the selector, it'll be omitted and work on the current document. A shorthand version of $(document).ready(function(){}) is $(function(){}); so you want:

$(function() {
    $('#test').click(function() {
        alert('clicked!');
    });
});

Upvotes: 6

MobileExperience
MobileExperience

Reputation: 63

$("#test").ready(function() {
    $("#test").click(function() {
         alert('clicked!');
     });
});

You have to set the click-function to the Test-object, instead of the whole document $(this).

Upvotes: 0

David
David

Reputation: 20063

$("#test").ready(function() {
    $("#test").click(function() {
        alert('clicked!');
    });
});

Upvotes: 2

Related Questions