情况有点像
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中它可能被视为一个新变量。
当前回答
其他替代方法,可能没有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
其他回答
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();
Use
el.addEventListener('click',
function(){
// this will give you the id value
alert(this.id);
},
false);
如果你想传递任何自定义值到这个匿名函数那么最简单的方法是
// this will dynamically create property a property
// you can create anything like el.<your variable>
el.myvalue = "hello world";
el.addEventListener('click',
function(){
//this will show you the myvalue
alert(el.myvalue);
// this will give you the id value
alert(this.id);
},
false);
在我的项目中完美地工作。希望这能有所帮助
这是个老问题了,但我今天也遇到了同样的问题。我发现的最干净的解决方法是使用咖喱的概念。
它的代码是:
someObj.addEventListener('click', some_function(someVar));
var some_function = function(someVar) {
return function curried_func(e) {
// do something here
}
}
通过命名curry函数,可以调用Object。removeEventListener在以后的执行时间取消注册eventListener。
您编写的代码绝对没有任何问题。some_function和someVar都应该是可访问的,以防它们在匿名的上下文中可用
function() { some_function(someVar); }
被创建。
检查警报是否为您提供了您一直在寻找的值,确保它可以在匿名函数的作用域内访问(除非您在addEventListener调用旁边有更多操作相同someVar变量的代码)
var someVar;
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
some_function(someVar);
}, false);
为什么不直接从事件的目标属性获取参数呢?
例子:
const someInput = document.querySelector('button'); someInput。addEventListener('click', myFunc, false); someInput。myParam = '这是我的参数'; 函数myFunc (evt) { window.alert (evt.currentTarget.myParam); } <button class="input">显示参数</button>
JavaScript是一种面向原型的语言,记住!