情况有点像
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。
情况有点像
var someVar = some_other_function();
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
问题是someVar的值在addEventListener的侦听器函数中是不可见的,在addEventListener中它可能被视为一个新变量。
当前回答
function. prototype.bind()是将目标函数绑定到特定作用域并可选地在目标函数中定义this对象的方法。
someObj.addEventListener("click", some_function.bind(this), false);
或者捕获一些词法范围,例如在循环中:
someObj.addEventListener("click", some_function.bind(this, arg1, arg2), false);
最后,如果目标函数中不需要this参数:
someObj.addEventListener("click", some_function.bind(null, arg1, arg2), false);
其他回答
只是想添加。如果有人正在添加一个更新复选框到事件监听器的函数,你将不得不使用事件。目标替换此来更新复选框。
如果我没有弄错的话,使用bind调用函数实际上创建了一个由bind方法返回的新函数。这将在以后给你带来问题,或者如果你想删除事件监听器,因为它基本上就像一个匿名函数:
// Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', myCallback);
someObject.removeEventListener('event', myCallback);
// Not Possible:
function myCallback() { /* code here */ }
someObject.addEventListener('event', function() { myCallback });
someObject.removeEventListener('event', /* can't remove anonymous function */);
记住这一点。
如果你正在使用ES6,你可以按照建议做,但更干净一点:
someObject.addEventListener('event', () => myCallback(params));
向eventListener的回调函数发送参数需要创建一个隔离函数并将参数传递给该隔离函数。
这里有一个很好的辅助函数。基于上面“hello world”的例子。)
还有一件事是维护对函数的引用,这样我们就可以干净地删除侦听器。
// Lambda closure chaos.
//
// Send an anonymous function to the listener, but execute it immediately.
// This will cause the arguments are captured, which is useful when running
// within loops.
//
// The anonymous function returns a closure, that will be executed when
// the event triggers. And since the arguments were captured, any vars
// that were sent in will be unique to the function.
function addListenerWithArgs(elem, evt, func, vars){
var f = function(ff, vv){
return (function (){
ff(vv);
});
}(func, vars);
elem.addEventListener(evt, f);
return f;
}
// Usage:
function doSomething(withThis){
console.log("withThis", withThis);
}
// Capture the function so we can remove it later.
var storeFunc = addListenerWithArgs(someElem, "click", doSomething, "foo");
// To remove the listener, use the normal routine:
someElem.removeEventListener("click", storeFunc);
您可以通过将函数声明为变量来添加和删除带有参数的事件侦听器。
myaudio.addEventListener(’ended’、funcName =功能(false) (newSrc myaudio)});
newSrc是以myaudio为参数的方法 funcName是函数名变量
可以使用删除侦听器 myaudio.removeEventListener(“结束”,func假);
2019年,很多api发生了变化,最好的答案不再有效,没有修复错误。
分享一些工作代码。
受到以上所有答案的启发。
button_element = document.getElementById('your-button')
button_element.setAttribute('your-parameter-name',your-parameter-value);
button_element.addEventListener('click', your_function);
function your_function(event)
{
//when click print the parameter value
console.log(event.currentTarget.attributes.your-parameter-name.value;)
}