JavaScript 事件目标
JavaScript event target
我对事件目标有疑问。我想检查单击了哪个元素,但它不起作用。这个问题的解决方案是什么?
var prod = document.querySelectorAll("button");
function dodaj(e) {
var tar = e.target;
console.log(tar);
}
for(var i = 0; i < prod.length; i++) {
prod[i].addEventListener("click", function() {
dodaj();
}, false);
}
您还没有向 dodaj
传递任何内容。您可以直接将 dodaj
传递给 addEventListener
.
prod[i].addEventListener("click", dodaj, false);
问题是您的点击事件处理程序是一个匿名函数,它正在调用执行该工作的实际函数 (dodaj
),而该函数没有接收到对该事件的引用 -匿名函数是。
您可以更改匿名函数,使其接收事件,然后将其传递给 dodaj
,如下所示:
prod[i].addEventListener("click", function(evt) {
dodaj(evt);
}, false);
但是,由于 "wrapper" 函数确实没有为您的代码添加任何值,您 can/should 将其完全删除并仅将实际的回调函数注册为点击事件处理程序。
var prod = document.querySelectorAll("button");
function dodaj(e) {
console.log(e.target);
}
for(var i = 0; i < prod.length; i++) {
// When any button gets clicked, call the dodaj function
// directly. This is the function that will receive a
// reference to the click event.
prod[i].addEventListener("click", dodaj);
}
<button id="one">Click Me</button>
<button id="two">Click Me</button>
<button id="three">Click Me</button>
<button id="four">Click Me</button>
我对事件目标有疑问。我想检查单击了哪个元素,但它不起作用。这个问题的解决方案是什么?
var prod = document.querySelectorAll("button");
function dodaj(e) {
var tar = e.target;
console.log(tar);
}
for(var i = 0; i < prod.length; i++) {
prod[i].addEventListener("click", function() {
dodaj();
}, false);
}
您还没有向 dodaj
传递任何内容。您可以直接将 dodaj
传递给 addEventListener
.
prod[i].addEventListener("click", dodaj, false);
问题是您的点击事件处理程序是一个匿名函数,它正在调用执行该工作的实际函数 (dodaj
),而该函数没有接收到对该事件的引用 -匿名函数是。
您可以更改匿名函数,使其接收事件,然后将其传递给 dodaj
,如下所示:
prod[i].addEventListener("click", function(evt) {
dodaj(evt);
}, false);
但是,由于 "wrapper" 函数确实没有为您的代码添加任何值,您 can/should 将其完全删除并仅将实际的回调函数注册为点击事件处理程序。
var prod = document.querySelectorAll("button");
function dodaj(e) {
console.log(e.target);
}
for(var i = 0; i < prod.length; i++) {
// When any button gets clicked, call the dodaj function
// directly. This is the function that will receive a
// reference to the click event.
prod[i].addEventListener("click", dodaj);
}
<button id="one">Click Me</button>
<button id="two">Click Me</button>
<button id="three">Click Me</button>
<button id="four">Click Me</button>