admin管理员组

文章数量:1391999

this to call each 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>

this to call each 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>
Share Improve this question edited Jan 24, 2011 at 3:28 Phrogz 304k113 gold badges667 silver badges757 bronze badges asked Jan 24, 2011 at 3:11 theHacktheHack 2,0049 gold badges27 silver badges34 bronze badges 1
  • 1 Conceptually, you should not assign the same ID to more than one elements. Also, the attribute "mnuid" is not valid. Why don't you change that "mnuid" to "id" ? – doc_id Commented Jan 24, 2011 at 3:28
Add a ment  | 

1 Answer 1

Reset to default 8

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);
}

本文标签: javascriptaddEventListener() when the id isn39t specifiedStack Overflow