addEventListener() when the id isn't specified
this to call eac开发者_开发知识库h of the top menu
var arrayTop=document.getElementById("topmenu").getElementsByTagName("a");
for (i=0;i<arrayTop.length;i++){
document.getElementById(arrayTop[i].id).addEventListener("click",topMenu,false);
}
the HTML
<div id="topmenu">
<a id="help" href=#><span>Help</span></a>
<a id="frum" href=#><span>Forum</span></a>
<a id="home" href=#><span>Home</span></a>
</div>
but,how to apply addEventListener() when the id isn't specified? since some of the elements will have the same id. so i'll change the id attribute to be
<div id="topmenu">
<a mnuid="help" href=#><span>Help</span></a>
<a mnuid="frum" href=#><span>Forum</span></a>
<a mnuid="home" href=#><span>Home</span></a>
</div>
You don't need the id. You already have the elements from the call to getElementsByTagName
.
var arrayTop = document.getElementById("topmenu").getElementsByTagName("a");
for (var i = 0; i < arrayTop.length; i++)
{
arrayTop[i].addEventListener("click",topMenu,false);
}
精彩评论