JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

17.2.3 addEventListener()

17.2.3 addEventListener()


In the standard event model supported by all browsers other than IE8 and earlier, any object that can be an event target—this includes the Window and Document objects and all document Elements—defines a method named addEventListener() that you can use to register an event handler for that target. addEventListener() takes three arguments. The first is the event type for which the handler is being registered. The event type (or name) is a string and it should not include the “on” prefix that is used when setting event handler properties. The second argument to addEventListener() is the function that should be invoked when the specified type of event occurs. The final argument to addEventListener()is a boolean value. Normally, you’ll pass falsefor this argument. If you pass true instead, your function is registered as a capturing event handler and is invoked at a different phase of event dispatch. We’ll cover event capturing in §17.3.6 . You ought to be able to omit the third argument instead of passing false, and the specification may eventually change to allow this, but at the time of this writing, omitting that argument is an error in some current browsers.

The code below registers two handlers for the click event on aelement. Note the differences between the two techniques used:

Click me

Calling addEventListener() with “click” as its first argument does not affect the value of the onclick property. In the code above, a button click will generate two alert() dialog boxes. More importantly, you can call addEventListener() multiple times to register more than one handler function for the same event type on the same object. When an event occurs on an object, all of the handlers registered for that type of event are invoked, in the order in which they were registered. Invoking addEventListener() more than once on the same object with the same arguments has no effect—the handler function remains registered only once, and the repeated invocation does not alter the order in which handlers are invoked.

addEventListener() is paired with a removeEventListener() method that expects the same three arguments but removes an event handler function from an object rather than adding it. It is often useful to temporarily register an event handler and then remove it soon afterward. For example, when you get a mousedown event, you might register temporary capturing event handlers for mousemove and mouseup events so that you can see if the user drags the mouse. You’d then deregister these handlers when the mouseup event arrives. In such a situation, your event handler removal code might look like this:

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/28026.html
友情链接It题库(ittiku.com)| 版权归yishouce.com所有| 友链等可联系 admin#yishouce.com|粤ICP备16001685号-1