Checkboxes are being checked before click handler

2019-02-19 08:03发布

问题:

I have the following snippets: http://jsfiddle.net/L7rne/5/ and http://jsfiddle.net/L7rne/6/

It turns out that if you pause execution of the script in the click event handler, then the checkbox is checked, even though there is event.preventDefault().

I tried this in Firefox 7 and Chrome 15 and both behave in the same way.

I'm almost sure that it's a correct behaviour but somehow I cannot find any reference why it's like that.

Could someone point me in the right direction?

EDIT:

When you start with checked checkboxes then it becomes even more interesting: http://jsfiddle.net/L7rne/8/ - the checkbox becomes unchecked but its value stays checked http://jsfiddle.net/L7rne/9/ - the checkbox becomes unchecked but its value becomes false

(This is consistent with pure Javascript code using checkbox.checked and checkbox.getAttribute('checked'), so I'm not pasting another jsfiddle snippets)

EDIT2:

COBOLdinosaur in one of the comments pointed me to this: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-cancelation, but IMHO that only confirms my point of view...

回答1:

not sure I'm understanding the problem. why wouldn't it be the right behaviour?

seriously, let's say you write some code that shows/hides a div based on whether a checkbox is ticked or not.

so, you write an onclick. if the checkbox is unticked, and then you click it, what do you think should be done to the div? obviously, you would expect the event to find the checkbox to be checked.



回答2:

By time the event handler fires, the event has already taken place, and the browser is re-rendering in response. If the handler gets suspended, then the browser completes the work because nothing prevented it.

Its like calling the police to a bank robbery, and they are in a traffic accident on the way. The robbers get away. The deed is done.