开发者

Question regarding jQuery click() function

    $('document').ready(function(){
        $('[name=mycheckbox]').live('click', function(){
            if($(this).is(':checked'))
            {
                alert('it is checked');
            }
            else
            {
                alert('it is not checked');
            }
        });

        $('[name=mycheckbox]').click();
    });

If the checkbox is checked and you click it, the alert box says, "it is not checked", but when the page runs and the click event is fired (with the checkbox checked), the alert box says, "it is checked". Why? Is the state of the checkbox not effected by the click event? Is it mousedown that chan开发者_运维百科ges the state?


Instead of click you should use the change event here, like this:

$('[name=mycheckbox]').live('change', function(){

And invoke it with the same trigger, like this:

$('[name=mycheckbox]').change();

The click is separate from the change, if you want the event to fire when the check actually has finished changing, then you want change, not click. Alternately, if you want to toggle it from it's initial state still, do this:

$('[name=mycheckbox]').click().change();


Instead of the live event (which I've found to be buggy at best) try binding a normal click even instead. I've done something similar which works fine with a .click event not .live("click",

I hope that helps :S


What is happening is quite subtle.

I have a button and checkbox linked to the following code:

$("#chkbx").click(function() {

    if ($(this).is(':checked')) {
        alert('checked');
    }
    else {
        alert('unchecked');
    }
});

$("#MyButton").click(function() {

    $("#chkbx").click();
});

When I click on the checkbox, everything is displayed as you would expect.

When I click on the button, the reverse is true.

What is happening, is that when you click on the checkbox, it is firing the default click event before executing your code, and thus you code is taking the status from the aftermath of the default click event.

When you call the click method directly on the element, it is actually calling your click function and then executing the default event.

I'm not why this should be. or if this is intentional, or a bug.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜