Javascript单击多个元素上的事件侦听器并获取目标ID [英] Javascript click event listener on multiple elements and get target ID
问题描述
我有一个JavaScript文件,通过< article>
标签在每个元素上设置一个点击的EventListener。我希望获得事件发生时点击的文章的ID。由于某种原因,我的代码没有产生任何东西!
我的javascript:
articles = document.getElementsByTagName('article');
articles.addEventListener('click',redirect(e),false);
函数重定向(e){
alert(e.target.id);
}
为什么这不起作用?顺便说一句,我的文章设置是在窗口加载时调用的一个函数中,我知道这是可行的,因为该函数还有其他工具可以使用。
编辑
因此,我修复了我的代码,以便循环并将侦听器添加到每个文章元素,现在我收到一个没有任何内容的警告框。当试图输出不带ID的e.target时,我会为每个元素得到以下消息:
[object HTMLHeadingElement]
有何建议?
另一个编辑
我目前的javascript代码:
函数doFirst(){
articles = document.getElementsByTagName('article');
for(var i = 0; i< articles.length; i ++){
articles [i] .addEventListener('click',redirect(articles [i]),false);
}
}
函数重定向(e){
alert(e.id);
}
window.addEventListener('load',doFirst,false);
当页面完成加载时,这会显示我的警告框,而不考虑我没有点击过该死的东西:O
您没有将文章对象作为参数传递给重定向。
试试这个(编辑):
articles = document.getElementsByTagName( '文章');
for(var i = 0; i< articles.length; i ++){
articles [i] .addEventListener('click',redirect,false);
}
函数重定向(ev){
alert(ev.target.id);
}
希望它能解决这个bug。
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
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.
这篇关于Javascript单击多个元素上的事件侦听器并获取目标ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!