Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

html - Javascript click event listener on multiple elements and get target ID

I have a javascript file that sets an EventListener of 'click' on every element with the <article> tag. I want to get the id of the article clicked when the event fires. For some reason, my code produces nothing!

My javascript:

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

Why isn't this working? BTW my article setup is in a function called when the window is loaded, and i know that works for sure because that function has other stuff that work.


EDIT

So i fixed my code so it will loop and add the listener to every article element, and now i get an alert box with nothing in it. When trying to output the e.target without the ID, i get the following message for every element:

[object HTMLHeadingElement]

Any suggestions?


ANOTHER EDIT

My current javascript code:

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

function redirect(e){
alert(e.id);
}
window.addEventListener('load',doFirst,false);

This is showing my alert boxes when the page finished loading, without considering that i haven't clicked a damn thing :O

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...