简体   繁体   中英

How can I pass a custom argument to an event listener in JavaScript?

How can I add an event listener (addEventListener(),attachEvent()) that also accepts a parameter?

The parameter is passed as the element's custom attribute like:

<img src="icon.gif" alt="Test button" command="test" />
<img src="icon2.gif" alt="Test button2" command="write" />

您可以在处理程序中使用getAttribute,例如

var param = this.getAttribute('command');

You could use something like this:

element.addEventListener ( 'click', (function ( myParam ) {
    return function () {
        // user myParam here
    };
} ) ( yourParam ), false );

whatever you pass in as "yourParam" will be accessible to the event handler via the "myParam" parameter ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM