情况有点像
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 Name()
{
this.methodName = "Value"
}
就是这样。 这对我很管用。 那么简单。
其他回答
不错的一行选择
element.addEventListener('dragstart',(evt) => onDragStart(param1, param2, param3, evt));
function onDragStart(param1, param2, param3, evt) {
//some action...
}
$form.addEventListener('submit', save.bind(null, data, keyword, $name.value, myStemComment));
function save(data, keyword, name, comment, event) {
这就是我如何正确地传递事件。
您可以通过将函数声明为变量来添加和删除带有参数的事件侦听器。
myaudio.addEventListener(’ended’、funcName =功能(false) (newSrc myaudio)});
newSrc是以myaudio为参数的方法 funcName是函数名变量
可以使用删除侦听器 myaudio.removeEventListener(“结束”,func假);
向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);
其他替代方法,可能没有bind的使用那么优雅,但它对于循环中的事件是有效的
for (var key in catalog){
document.getElementById(key).my_id = key
document.getElementById(key).addEventListener('click', function(e) {
editorContent.loadCatalogEntry(e.srcElement.my_id)
}, false);
}
它已经测试了谷歌chrome扩展和可能e.srcElement必须替换为e.srcElement在其他浏览器
我发现这个解决方案使用Imatoria发布的评论,但我不能标记为有用的,因为我没有足够的声誉:D