复选框的更改和单击事件之间的jQuery区别 [英] jQuery difference between change and click event of checkbox
问题描述
正如标题所示,我想知道复选框的 change
和 click
事件之间的区别(在 jQuery 中)
As title suggests I want to know the difference between the change
and click
event of checkbox (in jQuery)
我已经阅读了这个什么的答案复选框上的 .click 和 .change 之间的区别
但是,它对我不起作用.change
即使我在不失去焦点的情况下击中空格也会触发.
But, its not working for me. change
fires even when I hit spaces without losing focus.
这是一个小提琴演示
两者的工作方式似乎相似.我在这里遗漏了什么吗?
Both seems to be working alike. Am I missing something here ?
推荐答案
根据 W3C 的规定,onclick
事件是由键盘触发的,用于辅助功能:
According to the W3C, the onclick
event is triggered by the keyboard for accessibility purposes:
SCR35:通过使用锚点和按钮的 onclick 事件使操作键盘可访问
为了给那些不使用鼠标的用户提供更好的用户体验,浏览器被开发来触发 onclick
事件,即使 click 发生在键盘.
In order to provide a better user experience for those without the use of a mouse, browsers have been developed to fire the onclick
event even if the click occurs with a keyboard.
因此,即使使用键盘的空格键点击复选框,jQuery的click
事件也会触发.change
,显然,每次复选框的状态改变时都会触发.
For this reason, jQuery's click
event will fire even if the checkbox is clicked by using the keyboard's spacebar. change
, obviously, will fire every time the checkbox's state changes.
复选框恰好是 change
和 click
可以互换的特殊情况,因为你不能在没有的情况下触发 change
事件也触发 click
.
The checkbox just happens to be the special case where change
and click
are interchangable, because you can't fire the change
event without also triggering click
.
当然,这条规则的例外是如果您要使用 javascript 手动更改复选框,例如:
Of course, the exception to this rule is if you were to use javascript to manually alter the checkbox, such as:
/* 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/
Here's a demonstration of these different actions: http://jsfiddle.net/jackwanders/MPTxk/1/
希望这会有所帮助.
这篇关于复选框的更改和单击事件之间的jQuery区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!