简体   繁体   English

在具有循环和jQuery的同一类的所有元素上添加Click事件

[英]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: 一些注意事项:

  • FWIW, the usual name for the event parameter in an event handler is event or e , not click . FWIW,事件处理程序中事件参数的常用名称是evente ,而不是click
  • Elements can have multiple classes, which will all be in 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM