[英]Adding Click event on all elements with the same class without loop and jQuery
我必须编写一个代码,在没有循环和jquery的同一类的所有输入上运行click事件。
我想出的是:
document.body.addEventListener('click', function (click) {
if (click.target.className == 'abc') {
document.frame.screen.value += this.value;
}
});
和单击的作品,但我得到undefined
而不是单击的输入包含的值。
和单击的作品,但我得到未定义,而不是单击的输入包含的值。
因为您在获取值时使用了this
而不是click.target
; 您想使用click.target
:
document.frame.screen.value += click.target.value;
// Here -----------------------^^^^^^^^^^^^
this
在您的处理程序中将为document.body
。 检查类时已正确使用click.target
,但获取值时未正确使用click.target
。
一些注意事项:
event
或e
,而不是click
。 className
。 如果这对您来说可能是个问题,则可以.classList.contains("abc")
。 ( classList
在所有现代浏览器上均可用,并且您可以在过时的浏览器上classList
。) input
元素不是问题,但是在将来,如果您想使用可以包含后代元素的元素,则可能需要使用循环来处理单击目标元素的后代的可能性:
var node = event.target; while (!node.classList.contains("abc")) { if (node === this) { return; // The click didn't pass through a matching element } node = node.parentNode; } // Use it here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.