Javascript click event listener on multiple elements and get target ID

前端 未结 6 1301
轻奢々
轻奢々 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: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);
    }
    

提交回复
热议问题