0

This is such a basic question but I am having trouble finding the answer - How do I implement the action taken when a list item in an Html menu is clicked?

I’m using an list in my code as a menu, say:

<ul  >
<li id="link1"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
  <ul class="level2">
    <li><a href="#">Link 2a</a></li>
    <li><a href="#">Link 2b</a></li>
    <li><a href="#">Link 2c</a></li>
  </ul></li>
</ul>

I tried giving the menu an id, id="myMenu", and an onclick event, and the js was called, but I couldn’t see a way to identify which item was clicked, just that an line item was clicked in myMenu.

<ul id="myMenu" onclick="gothere(id)">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
  <ul class="level2">
    <li><a href="#">Link 2a</a></li>
    <li><a href="#">Link 2b</a></li>
    <li><a href="#">Link 2c</a></li>
  </ul></li>
</ul>

<script type="text/javascript">
function gothere(id)
{
alert("got here "+id) ; 
}
</script>  

I tried adding an id on a child element, id="link1", and that worked, but the js was called for the child and then for the parent.

<ul id="myMenu" onclick="gothere(id)">
<li id="link1" onclick="gothere(id)"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
  <ul class="level2">
    <li><a href="#">Link 2a</a></li>
    <li><a href="#">Link 2b</a></li>
    <li><a href="#">Link 2c</a></li>
  </ul></li>
</ul>

I can use this approach to get what I need but is there a better way?

I am looking for something which sends the least amount of html over the wire (the reason I am redoing this menu from it's former implementation).

4

3 回答 3

1

识别处理程序中的元素目标或 srcElement,不要传递参数:

document.getElementById("myMenu").onclick=goThere;

function goThere(e){
  e= e || window.event;
  var who=e.target || e.srcElement;
  if(who.tagName=='LI'){
    //handle the clicked list item

  }
}
于 2012-09-19T17:27:33.687 回答
1

您不应该内联附加事件。用 javascript 附加它们。

<ul id="myMenu">
<li id="link1"><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a>
  <ul class="level2">
    <li><a href="#">Link 2a</a></li>
    <li><a href="#">Link 2b</a></li>
    <li><a href="#">Link 2c</a></li>
  </ul></li>
</ul>​

请注意,为了简单起见,我在这里使用 jQuery:

$("#myMenu").click(function(e){
    console.log(e.target);
});​

http://jsfiddle.net/2rjgd/

与 vanilla javascript 的概念是相同的,使用对象的target属性event来找出click事件的来源。

http://jsfiddle.net/2rjgd/1/展示了如何使用 vanilla js 实现这一点。(在非 IE 浏览器中)

document.getElementById("myMenu").addEventListener("click", function(e){
    console.log(e.target);
});​
于 2012-09-19T17:06:38.393 回答
0

无论哪种方式,您都需要一种方法来识别被单击的元素。Shmiddty 为您提供了查找按名称单击的元素的目标的方法。然后,您可以编写 if/then 语句来打开窗口或根据特定名称跟踪链接。

这可能比仅仅为元素分配 ID 并检查它们更困难/更复杂。您可以在 vanilla js 中执行此操作,使用如下语句:

var myLink1 = document.getElementById("link1");
myLink1.onclick=window.open("http://www.webaddresshere.com","_self");

如果可以的话,我的建议是使用 JQuery。它可以让你做这样的事情:

$('li[id^=link1]').click(window.open("http://www.webaddresshere.com","_self"));
于 2012-09-19T17:16:24.490 回答