疑似JavaScript点击事件并发问题
我正在使用这段 jQuery 向复选框添加单选按钮行为,即只允许检查每组中的一个。
$("input:checkbox").click(function()
{
$("input:checkbox:checked[name='" + this.name + "']")
.not(this).removeAttr("checked");
});
它工作得很好,或者至少我是这么认为的,直到我发现在 Opera 中,如果我坚持的话,我仍然可以选中同一组中的多个复选框。通过在一些复选框之间快速切换(像疯子一样点击),我最终会选中两个(或更多)复选框。
通常我认为 JavaScript 是单线程的,但我对此感到有点惊讶。然而,我知道 JavaScript 并不总是像看起来那样单线程(参见 这个答案),我认为这在某种程度上导致了这种行为。否则怎么可能发生呢?
如果我的假设是正确的,谁能解释一下发生了什么?在我链接到的答案中,您可以阅读:
类似地,在元素上调用 click() 会立即在所有浏览器中调用 onclick 处理程序(至少这是一致的!)。
这似乎是相关的,只不过这只发生在 Opera 上(我已经尝试过 IE(8)、FF、Chrome 和 Safari)。
任何意见都非常感谢!
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 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你点击这里的速度非常快,
http://jsfiddle.net/RxbW6/1/
你会看到当 2 个复选框最终被选中时同时检查(通过垃圾邮件),第二个复选框不会触发单击事件。因此,这不是 2 个单击事件干扰的线程问题,而是 Opera 似乎根本没有触发 onclick 事件。
我建议只使用无线电组并对其进行样式设计,这种情况就是它的用途。
但是,
会解决您的问题。
[编辑] mouseup 可能会更好,因此您可以 mousedown 然后移开并保留之前的检查。
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,
Will fix your issue.
[Edit] mouseup will probably be better so you can mousedown and then move off and keep the previous check.