Is there a standard for the event order of click a

2020-02-10 03:09发布

问题:

I've noticed that the order of 'click' and 'change' events are different in Chrome and Firefox.

See this JSFiddle for example: http://jsfiddle.net/5jz2g/3/

JavaScript:

var el = $('foo');
var fn = function(e) {
    console.log(e.type);
}
el.addEvent('change', fn);
el.addEvent('click', fn);

In Chrome this logs:

change
click

And in Firefox this logs:

click
change

Is there a standard for the order of events? Which should fire first? The MDN doesn't seem to mention this and I couldn't find a thing about this in the W3C documents.

回答1:

DOM3 Events document has a recommendation about events order. According to it, in case of checkbox, the correct order will be click then change and not vice versa, because change event obviously is a part of default actions for checkbox, see Example 5 and fiddle, which works as expected in FF but not in Chrome. That's logical, anyway. But! Let's read default actions section carefully:

Default actions should be performed after the event dispatch has been completed, but in exceptional cases may also be performed immediately before the event is dispatched.

Did you see that? W3C uses RFC's words SHOULD and MAY in one sentence! Nothing to be done, they're cautious guys. IMO, that's why we have what we have :)



回答2:

No, but if you want to make it consistent, you can fire one event off the other rather than having them fire separately since for a check box and change amount to the same event...or perhaps you could use an interval timer to to delay the response on one of the events.



回答3:

try this

$(function(){

    var $select = $('foo');
    var store = function(e) {
        console.log(e.type);
    };

    $select.addEvent('change', store).addEvent('click', store);

});

http://jsfiddle.net/donddoug/Du7z5/



回答4:

Couldn't find a way to sync events cross browser...

the following does work in the same order in both FF and Chrome;

JavaScript Code (use mouseup / mousedown to catch the "click"):

var el = $('foo');
var fn = function(e) {
    console.log(e.type);
}
el.addEvent('change', fn);
el.addEvent('mouseup', fn);

http://jsfiddle.net/5jz2g/17/