我正在尝试向循环中的元素添加事件侦听器,但我正在努力使参数正确传递给匿名函数。
以下是我正在尝试将js应用到的HTML的示例:
<button data-messagesend="Hello!">Send Hello</button>
<button data-messagesend="Goodbye!">Send Goodbye</button>
这是js:
// sendMsg function that will be applied to elements as an event listener
function sendMsg(msg) {
console.log(msg);
}
//Get all elements that have the data-sendmessage property
elts=document.querySelectorAll('[data-messagesend]');
//Create global array for messages
var messages=[];
//Loop through elements and add an event listener to call sendMsg with it's massage
for(i=0;i<elts.length;i++) {
//add element data-sendmessage value to messages array
messages[i]=elts[i].dataset.messagesend;
//add event listener
elts[i].addEventListener('click',function(){sendMsg(messages[i]);}.bind(messages[i]),false);
}
这是我正在努力的//add event listener
行
我也试过了:
elts[i].addEventListener('click',function(){sendMsg(messages[i]);}.bind(messages,i),false);
和
elts[i].addEventListener('click',(function(msg){sendMsg(msg);})(messages[i]),false);
但是当点击按钮时它只返回undefined
。
任何帮助都会很棒:D
小提琴
答案 0 :(得分:1)
有几种方法可以实现这一目标。第一个,由@Tushar在评论中回答(和jFiddle here),它使用正确的方法来使用附件:
// sendMsg function that will be applied to elements as an event listener
function sendMsg(msg) {
console.log(msg);
}
//Get all elements that have the data-sendmessage property
elts = document.querySelectorAll('[data-messagesend]');
//Create global array for messages
var messages = [];
//Loop through elements and add an event listener to call sendMsg with it's massage
for (i = 0; i < elts.length; i++) {
(function (i) {
//add element data-sendmessage value to messages array
messages[i] = elts[i].dataset.messagesend;
console.log(messages);
//add event listener
elts[i].addEventListener('click', function () {
sendMsg(messages[i]);
}, false);
}(i));
}
然后第二种方式,由@Barmar引用答案here,它改变了sendMsg
函数以获取数据集信息:
// sendMsg function that will be applied to elements as an event listener
function sendMsg(msg) {
msg=this.dataset.messagesend||msg;
console.log(msg);
}
//Get all elements that have the data-sendmessage property
elts=document.querySelectorAll('[data-messagesend]');
//Loop through elements and add an event listener to call sendMsg
for(i=0;i<elts.length;i++) {
elts[i].addEventListener('click',sendMsg,false);
}
我偏爱第一个解决方案的原因是需要在第二个解决方案中更改sendMsg
函数。这在所有情况下都是不可能的,例如使用外部js脚本中的函数。