开发者

Suspected JavaScript click event concurrency issue

I'm using this piece of jQuery to add radio button behavior to checkboxes, i.e. allowing only one from each group to be checked.

$("input:checkbox").click(function()
{
    $("input:checkbox:checked[name='" + this.name + "']")
        .not(this).removeAttr("checked");
});

It works great, or at least I thought so until I discovered that in Opera I can still check multiple checkboxes from the same group if I'm insistent. By rapidly toggling between some checkboxes (clicking like a maniac) I eventually end up with two (or more) checked.

Normally thinking of JavaScript as single-threaded I was kind of surprised开发者_JS百科 by this. However, I know JavaScript is not always as single-threaded as it seems (see this answer) and I assume that's somehow causing this behavior. How can it otherwise happen?

If my assumption is right, can anyone explain what happens? In the answer I link to you can read:

Similarly calling click() on an element that provides it calls the onclick handler immediately in all browsers (at least this is consistent!).

That seems relevant, except that this only happens with Opera (I've tried with IE(8), FF, Chrome and Safari).

Any input is much appreciated!


If you click really fast here, http://jsfiddle.net/RxbW6/1/

You will see that when 2 checkboxes end up being checked at the same time (by spamming them) the click event does not fire for the second checkbox. So it's not a threading issue with the 2 click events interfering, rather opera does not seem to be firing the onclick event at all.

I would recommend just using a radio group instead and styling it, this case is what it is here for.

However,

$("input:checkbox").mouseup(function()
{
    $("input:checkbox:checked[name='" + this.name + "']")
        .not(this).removeAttr("checked");
});

Will fix your issue. [Edit] mouseup will probably be better so you can mousedown and then move off and keep the previous check.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜