如标题所示,我想知道复选框的 change
和 click
事件之间的区别(在 jQuery 中)
我已经阅读了这个 What the difference between .click and .change on a checkbox 的答案
但是,它对我不起作用。 change
即使我在没有失去焦点的情况下点击空格也会触发。
这是一个 fiddle demo
两者的工作原理似乎相似。我在这里遗漏了什么吗?
最佳答案
根据 W3C,onclick
事件由键盘触发以实现辅助功能:
SCR35: Making actions keyboard accessible by using the onclick event of anchors and buttons
为了给那些不使用鼠标的用户提供更好的用户体验,浏览器被开发为触发 onclick
事件,即使 click 发生在键盘。
因此,即使使用键盘的空格键单击复选框,jQuery 的click
事件也会触发。 change
,显然,每次复选框的状态改变时都会触发。
复选框恰好是 change
和 click
可以互换的特殊情况,因为你不能触发 change
事件还会触发 click
。
当然,此规则的异常(exception)情况是您使用 javascript 手动更改复选框,例如:
/* this would check the checkbox without firing either 'change' or 'click' */
$('#someCheckbox').prop('checked',true);
/* this would fire 'change', but not 'click'. Note, however, that this
does not change the checkbox, as 'change()' is only the function that
is fired when the checkbox changes, it is not the function that
does the changing */
$('#someCheckbox').trigger('change');
/* this would fire 'click', which by default change state of checkbox and automatically triggers 'change' */
$('#someCheckbox').trigger('click');
下面是这些不同操作的演示:http://jsfiddle.net/jackwanders/MPTxk/1/
希望这对您有所帮助。
关于javascript - jQuery 复选框的更改和单击事件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11205957/