简体   繁体   中英

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.

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.

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; you wanted to use click.target :

document.frame.screen.value += click.target.value;
// Here -----------------------^^^^^^^^^^^^

this in your handler will be document.body . You've correctly used click.target when checking the class, but not when getting the value.

Some notes:

  • FWIW, the usual name for the event parameter in an event handler is event or e , not click .
  • Elements can have multiple classes, which will all be in className . If that's a possible issue for you, you might look at .classList.contains("abc") instead. ( classList is available on all modern browsers, and you can polyfill it on obsolete ones.)
  • 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:

     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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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