繁体   English   中英

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

[英]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

一些注意事项:

  • FWIW,事件处理程序中事件参数的常用名称是evente ,而不是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.

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