简体   繁体   English

将元素传递给事件侦听器回调函数

[英]Pass Element to Event Listener Callback Function

In the following code:在以下代码中:

document.getElementById( 'elem' ).addEventListener( 'blur', function() {
    myScript();
});

How can I pass the document.getElementById( 'elem' ) object to myScript()?如何将 document.getElementById('elem') 对象传递给 myScript()? I was thinking of something like the keyword "this," so I can then act on the element in the callback function.我在想像关键字“this”这样的东西,这样我就可以对回调函数中的元素采取行动。

You have four ways to pass the object this您有四种方法可以将对象传递给this

Bind the this object and call the function:绑定this对象并调用函数:

This approach should be used if you need to execute some logic before myScript() execution如果您需要在myScript()执行之前执行一些逻辑, myScript()使用此方法

 function myScript() { console.log(this.id); } document.getElementById('elem').addEventListener('click', function() { myScript.bind(this)(); });
 <button id="elem">Click me!</button>

Call the function myScript using function call :使用函数call函数myScript

This approach should be used if you need to execute some logic before myScript() execution如果您需要在myScript()执行之前执行一些逻辑, myScript()使用此方法

Also read about function Function.prototype.apply() .另请阅读函数Function.prototype.apply()

 function myScript() { console.log(this.id); } document.getElementById('elem').addEventListener('click', function() { myScript.call(this); });
 <button id="elem">Click me!</button>

Pass the function directly:直接传递函数:

 function myScript() { console.log(this.id); } document.getElementById('elem').addEventListener('click', myScript);
 <button id="elem">Click me!</button>

Or pass the object this :或传递对象this

 function myScript(element) { console.log(element.id); } document.getElementById('elem').addEventListener('click', function() { myScript(this); //Here you will need to use the param. });
 <button id="elem">Click me!</button>

Resource资源

Further to the answer from Ele, you should prefer the binding method.除了 Ele 的回答之外,您应该更喜欢绑定方法。 As dfsq said in the comment, you can go正如dfsq在评论中所说,你可以去

element.addEventListener('click', function() {
    myScript(element);
}

However, using an anonymous function like this means you won't be able to remove the event listener.但是,使用这样的匿名函数意味着您将无法删除事件侦听器。

const element = document.getElementById('elem');
// creates a new function instance with element bound as first arg
const eventListenerCallback = myScript.bind(null, element);
element.addEventListener('click', eventListenerCallback);

function myScript(element, event) {
    element.setAttribute('data-clicked', 'true');
    // remove the event listener once it has been clicked
    element.removeEventListener('click', eventListenerCallback);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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