情况有点像
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中它可能被视为一个新变量。
当前回答
我建议你这样做:
var someVar = some_other_function();
someObj.addEventListener("click", (event, param1 = someVar) => {
some_function(param1);
}, false);
其他回答
因为你的事件监听器是'click',你可以:
someObj.setAttribute("onclick", "function(parameter)");
这个解决方案可能很好看
var some_other_function = someVar => function() {
}
someObj.addEventListener('click', some_other_function(someVar));
或者绑定变量也不错
如果以后想要删除事件侦听器,那么创建对curry函数的引用是一个不错的选择。
在下面的代码中,我将说明我的意思。
// This is the curry function. We return a new function with the signature of what the click-listener expects
const handleClick = (foo, bar) => (clickEvent) => {
console.log('we get our custom input', foo, bar);
console.log('we get the click event too', clickEvent);
}
// We need to store a reference to the listener, making sure we are removing the correct reference later
const myListener = handleClick('foo', 'bar'); // Remember that we now return the actual event-handler
const btn = document.getElementById('btn'); // find the element to attach the listener to
btn.addEventListener('click', myListener);
// remove the event listener like this by using our reference
btn.removeEventListener('click', myListener);
下面是CodePen上的一个工作示例
var EV = {
ev: '',
fn: '',
elem: '',
add: function () {
this.elem.addEventListener(this.ev, this.fn, false);
}
};
function cons() {
console.log('some what');
}
EV.ev = 'click';
EV.fn = cons;
EV.elem = document.getElementById('body');
EV.add();
//If you want to add one more listener for load event then simply add this two lines of code:
EV.ev = 'load';
EV.add();
其他替代方法,可能没有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