开发者

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=开发者_Go百科"Test button2" command="write" />


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 ...


You can use getAttribute in your handler, something like

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜