Javascript click event listener on multiple elements and get target ID

前端 未结 6 1280
轻奢々
轻奢々 2020-12-01 22:06

I have a javascript file that sets an EventListener of \'click\' on every element with the

tag. I want to get the id of the article clicked when
相关标签:
6条回答
  • 2020-12-01 22:12

    This mini javascript libary (1.3 KB) can do all these things

    https://github.com/Norair1997/norjs/

    nor.event(["#first"], ["touchstart", "click"], [doSomething, doSomething]);
    

    This plugin can handle such stuff and more

    0 讨论(0)
  • 2020-12-01 22:13

    Why is nobody mentioning a single event which checks for the clicked element?

    document.body.addEventListener('click', function(e) {
        var target = e.target;
        if (target.nodeName === 'article') {
            // do whatever you like ;-)
        }
        e.stopPropagation()
    });
    

    it's more performant to have less events..

    if you don't need to check for click events on the whole body you could attach the event to some closer parent element

    0 讨论(0)
  • 2020-12-01 22:16

    You are not passing an article object to redirect as a parameter.

    Try this (EDIT):

    articles = document.getElementsByTagName('article');
    for (var i = 0; i < articles.length; i++) {
        articles[i].addEventListener('click',redirect,false);
    }
    function redirect(ev){
        alert(ev.target.id);
    }
    

    Hope, it will solve the bug.

    0 讨论(0)
  • 2020-12-01 22:22
    articles.addEventListener('click',redirect,false); // omit redirect(e) inside event listener // and then try with the alert as you did.
    

    if does not work then try by e.id instead of e.target.id inside alert as below:

       alert(this.id);
    

    Thanks.

    0 讨论(0)
  • 2020-12-01 22:24

    getElementsByTagName returns a nodelist. You can then add an eventlistener to each one of those elements with a for loop.

    <div id="test">
    hey
    </div>
    <div id="test2">
    yo
    </div>
    
    <script>
    var nl = document.getElementsByTagName('div');
    
    for(var i=0; i<nl.length; i++){
        nl[i].addEventListener('click', function(e){
            alert(e.target.id);
        },false);
    }
    </script>
    
    0 讨论(0)
  • 2020-12-01 22:28

    You are executing the redirect function instead of passing the reference, try this:

    articles = document.getElementsByTagName('article');
    articles.addEventListener('click',redirect,false);
    function redirect(e){
        alert(e.target.id);
    }
    

    Edit: Also, getElementsByTagName returns an array with articles, so you have to loop through them and call addEventListener on each one of them.

    articles = document.getElementsByTagName('article');
    for (var i = 0; i < articles.length; i++) {
        articles[i].addEventListener('click',redirect,false);
    }
    function redirect(e){
        alert(e.target.id);
    }
    
    0 讨论(0)
提交回复
热议问题