gpt4 book ai didi

jQuery、Chrome 和复选框。奇怪的行为

转载 作者:行者123 更新时间:2023-12-03 22:15:07 24 4
gpt4 key购买 nike

我浏览了整个网站,似乎找不到这个问题的答案。如果确实存在,请随时引导我回答上述问题。

我目前正在尝试执行一些基于树的复选框操作,并且遇到了一些我觉得奇怪的行为。

在 Google Chrome 中,我发现选中复选框会留下一些“残留物”,如果您愿意的话,这将不允许我使用“attrRemove('checked');”选中或取消选中该复选框

有趣的是,Internet Explorer (9) 具有我想要的结果。请在 Chrome 和 IE 中查看此 jsFiddle,以更好地比较效果。

http://jsfiddle.net/xixionia/9K5ft/

任何人都可以解释这些差异,以及我如何能够选中/取消选中 chrome 中已“手动”选中的复选框吗?

HTML

<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />

JavaScript

$(':checkbox').click(function(e) {

if($(this).is(':checked')) {
$(':checkbox').attr('checked', 'checked');
} else {
$(':checkbox').removeAttr('checked');
}
});

预先感谢您的帮助。 :)

编辑:

我找到了这个解决办法。如果其他人有任何其他解决方案,请告诉我,我会将其标记为解决方案。 :)

$(':checkbox').click(function(e) {
var value = this.checked;
$(':checkbox').each(function(){ this.checked = value; });
});

编辑:

事实证明,这个问题是 jQuery 1.6 特有的。以前版本的 jQuery 不会遇到此问题。不过,我在这里发布了一个解决方案:Setting "checked" for a checkbox with jQuery?

最佳答案

当使用复选框(尤其是基于复选框的复杂逻辑)时,我总是尝试避免在复选框上使用 jQuery 事件处理程序。 jQuery 中有一个错误,与单击复选框和使用的浏览器时事件触发的顺序有关: 您可以找到部分问题的描述here 。引用:

It seems that when you trigger the click event on a checkbox, the default behavior (toggling the checked attribute) takes place after event handlers fire. This is opposite of what happens when the browser naturally handles the checkbox click event - the checked attribute is toggled and then the event handlers are executed. This difference in the order of operations between inherent clicking and jQuery's event triggering can cause a big problem if the event handler depends on the status of checkbox in anyway (which, if you have a click handler on a checkbox to begin with means it probably does).

jQuery 将此称为一项功能,因为它从一开始就存在,将其更改为正确的行为只会杀死许多现有的应用程序。我经常遇到复选框和“选中”的问题,只是因为事件触发得太晚了。所以我只使用原生JS方式: input.checked 。

关于jQuery、Chrome 和复选框。奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5907645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com