[英]Adding Click event on all elements with the same class without loop and jQuery
I have to write a code that run click event on all inputs with the same class without a loop and jquery. 我必须编写一个代码,在没有循环和jquery的同一类的所有输入上运行click事件。
What I come up with is : 我想出的是:
document.body.addEventListener('click', function (click) {
if (click.target.className == 'abc') {
document.frame.screen.value += this.value;
}
});
and click works but I got undefined
instead of value that clicked input contain. 和单击的作品,但我得到
undefined
而不是单击的输入包含的值。
and click works but I got undefined instead of value that clicked input contain.
和单击的作品,但我得到未定义,而不是单击的输入包含的值。
Because you've used this
instead of click.target
when getting the value; 因为您在获取值时使用了
this
而不是click.target
; you wanted to use click.target
: 您想使用
click.target
:
document.frame.screen.value += click.target.value;
// Here -----------------------^^^^^^^^^^^^
this
in your handler will be document.body
. this
在您的处理程序中将为document.body
。 You've correctly used click.target
when checking the class, but not when getting the value. 检查类时已正确使用
click.target
,但获取值时未正确使用click.target
。
Some notes: 一些注意事项:
event
or e
, not click
. event
或e
,而不是click
。 className
. className
。 If that's a possible issue for you, you might look at .classList.contains("abc")
instead. .classList.contains("abc")
。 ( classList
is available on all modern browsers, and you can polyfill it on obsolete ones.) classList
在所有现代浏览器上均可用,并且您可以在过时的浏览器上classList
。) It's not an issue for input
elements, but in future if you want to do this with elements that can have descendant elements, you might need to have a loop to handle the possibility the click was on a descendant of your target element: 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.