将元素传递给事件侦听器回调函数 [英] Pass Element to Event Listener Callback Function

查看:40
本文介绍了将元素传递给事件侦听器回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中:

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

如何将document.getElementById('elem')对象传递给myScript()?我当时在想像关键字"this"之类的东西,因此我可以对回调函数中的元素进行操作.

How can I pass the document.getElementById( 'elem' ) object to myScript()? I was thinking of something like the keyword "this," so I can then act on the element in the callback function.

推荐答案

您有四种方法来传递对象 this

绑定 this 对象并调用函数:

You have four ways to pass the object this

Bind the this object and call the function:

如果您需要在执行 myScript()执行

function myScript() {
  console.log(this.id);
}

document.getElementById('elem').addEventListener('click', function() {
  myScript.bind(this)();
});

<button id="elem">Click me!</button>

使用函数 call 调用函数 myScript :

Call the function myScript using function call:

如果您需要在执行 myScript()执行

也请阅读有关函数 Function.prototype.apply() .

function myScript() {
  console.log(this.id);
}

document.getElementById('elem').addEventListener('click', function() {
  myScript.call(this);
});

<button id="elem">Click me!</button>

直接传递该功能:

function myScript() {
  console.log(this.id);
}

document.getElementById('elem').addEventListener('click', myScript);

<button id="elem">Click me!</button>

或传递对象 this :

Or pass the object 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>

这篇关于将元素传递给事件侦听器回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆