Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

javascript - jQuery difference between change and click event of checkbox

As title suggests I want to know the difference between the change and click event of checkbox (in jQuery)

I have read down the answer to this What the difference between .click and .change on a checkbox

But, its not working for me. change fires even when I hit spaces without losing focus.

Here's a fiddle demo

Both seems to be working alike. Am I missing something here ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the W3C, the onclick event is triggered by the keyboard for accessibility purposes:

SCR35: Making actions keyboard accessible by using the onclick event of anchors and buttons

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.

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.

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.

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');

Here's a demonstration of these different actions: http://jsfiddle.net/jackwanders/MPTxk/1/

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...