从<ul onclick>获取Clicked <li>

cra*_*aft 22 html javascript html-lists

作为JS的相对初学者,我正在努力尝试找到解决方案.

我需要找出点击了无序列表的哪一行

<ul onclick="alert(this.clicked.line.id);">
  <li id=l1>Line 1</li>
  <li id=l2>Line 2</li>
  <li id=l3>Line 3</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我真的不想为每一行添加一个onclick事件,我敢肯定必须有办法?

Aro*_*eel 42

你可以使用event.target这个:

JS:

// IE does not know about the target attribute. It looks for srcElement
// This function will get the event target in a browser-compatible way
function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement; 
}

var ul = document.getElementById('test');
ul.onclick = function(event) {
    var target = getEventTarget(event);
    alert(target.innerHTML);
};
Run Code Online (Sandbox Code Playgroud)

HTML:

<ul id="test">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/ArondeParon/2dEFg/5/

请注意,这是一个非常基本的示例,当您将事件委托给包含多个级别的元素时,您可能会遇到一些问题.发生这种情况时,您必须向上遍历DOM树以查找包含元素.

  • +1这里的关键是将Javascript移出HTML属性。 (2认同)