AFAIK,addEventListener中的第二个参数是在事件发生后调用的确切函数名。我希望addEventListener中的第二个参数与字符串匹配,然后应该调用该函数。像:
var k =0;
for(var i=0;i<arr.length;i++){
var val=arr[i];
var link=document.createElement('a');
link.id='name'+k++;
link.innerHTML="Name : " +val.name+"<br/><br/>";
link.setAttribute('href','#');
link.addEventListener('click',link.id); //I want link.id should be the string which is either name0 or name1 or name2 ....
}
function name0(){
}
function name1(){
}
function name2(){
}
答案 0 :(得分:0)
我得到的是你想要动态地将点击事件和他们自己的处理程序添加到不同的元素。您可以使用他的方法执行此操作:
var k =0;
var obj = {
name0: function (){
},
name1: function(){
},
name2: function(){
}
}
for(var i=0;i<arr.length;i++){
var val=arr[i];
var link=document.createElement('a');
link.id='name'+k++;
link.innerHTML="Name : " +val.name+"<br/><br/>";
link.setAttribute('href','#');
//link.id could be name0, name1 ... and func could be obj[name0], obj[name1], obj[name2].....
link.addEventListener('click',obj[link.id]); //I want <br/> link.id should be the string which is either name0 or name1 or name2 ....
}
答案 1 :(得分:0)
最干净的方法是将事件侦听器包装在对象中,如下所示:
var arr = [{name: "zero"}, {name: "one"}];
var listeners = {
name0: function() {
alert("Name 0")
},
name1: function() {
alert("Name 1")
}
}
var k = 0;
for(var i=0; i < arr.length; i++){
var val = arr[i];
var link = document.createElement('a');
link.id = 'name' + k++;
link.innerHTML="Name: " + val.name + "<br/><br/>";
link.setAttribute('href','#');
link.addEventListener('click', listeners[link.id]);
document.body.appendChild(link);
}
提供小提琴here。