在下面的代码中:
document.getElementById( 'elem' ).addEventListener( 'blur', function() {
myScript();
});
如何将 document.getElementById( 'elem' ) 对象传递给 myScript()?我正在考虑类似关键字“this”的东西,这样我就可以对回调函数中的元素进行操作。
您有四种方法来传递对象this
绑定this
对象并调用函数:
如果您需要在之前执行一些逻辑,则应使用此方法myScript()
执行
function myScript() {
console.log(this.id);
}
document.getElementById('elem').addEventListener('click', function() {
myScript.bind(this)();
});
<button id="elem">Click me!</button>
调用函数myScript
使用功能call
:
如果您需要在之前执行一些逻辑,则应使用此方法myScript()
执行
另请阅读有关功能的信息Function.prototype.apply() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/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
:
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
- Function.prototype.bind() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
- Function.prototype.call() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
- Function.prototype.apply() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)