未指定id时的addEventListener()

时间:2011-01-24 03:11:24

标签: javascript html addeventlistener

这可以调用每个顶级菜单

var arrayTop=document.getElementById("topmenu").getElementsByTagName("a");
for (i=0;i<arrayTop.length;i++){
  document.getElementById(arrayTop[i].id).addEventListener("click",topMenu,false);
}

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>

但是,如果未指定id,如何应用addEventListener()? 因为一些元素将具有相同的id。所以我会将id属性更改为

<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>

1 个答案:

答案 0 :(得分:8)

您不需要ID。您已经拥有调用getElementsByTagName

的元素
var arrayTop = document.getElementById("topmenu").getElementsByTagName("a");
for (var i = 0; i < arrayTop.length; i++)
{
    arrayTop[i].addEventListener("click",topMenu,false);
}