Javascript click event listener on multiple elements and get target ID

前端 未结 6 1305
轻奢々
轻奢々 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: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.

提交回复
热议问题