What the difference between .click and .change on a checkbox [duplicate]

旧巷老猫 提交于 2019-11-26 04:25:58

问题


This question already has an answer here:

  • Getting value of HTML Checkbox from onclick/onchange events 3 answers

I was looking around to add an event to a checkbox and I would have thought people would use .change to set up a change event but instead I found that people are using .click

Is there a reason for this? They both seem to work fine both with clicked events and with keyboard changes. Am I missing something?

If you don\'t believe me then try it out yourself


回答1:


onchange in IE only fires when the checkbox loses focus. So if you tab to it, hit space a few times, tab out, you'll only get one onchange event, but several onclick events.

Note: this is one of the very, very, very rare times when IE's behavior is correct (according to spec) and other browsers are wrong.




回答2:


Two reasons why onclick is preferred over onchange.

  1. Internet Explorer only fires the onchange event when the checkbox loses the focus (onblur). So onclick is more of a cross browser solution.

  2. onchange happens only after the element lose focus.(You wont see a difference since you are calling alert and losing focus on every change). The pseudo code on MDC pretty much explains the element.onchange implementation.

    control.onfocus = focus;
    control.onblur = blur;
    
    function focus () {
        original_value = control.value;
    }
    
    function blur () {
        if (control.value != original_value)
            control.onchange();
    }
    



回答3:


.change doesn't work correctly for at least some popular browsers in relation to key changes (the user selecting option with up/down arrow keys) but then .click doesn't overcome this either. Sometimes the use of keyup or keydown or something is used in conjunction with .change to overcome this issue however it starts to get a bit messy when you user's tab the document as this can trigger the key event if it's not explicitly handled within the callback. All in all it's a shame that .change doesn't work as you would expect as it would solve some time consuming issues.




回答4:


yes both work, only click does not look at the actual object changing (like a checkbox that gets checked), change does.

Technically it is more reliable but in practise both work.




回答5:


They may both fire a change in the value by default, but you may override the onClick logic to NOT change the value of a chackbox. You may change the value via another entry point. So having a .click and a .change is needed.

edit - I also agree with Dr Rob



来源:https://stackoverflow.com/questions/5575338/what-the-difference-between-click-and-change-on-a-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!