获取点击< li>从< ul onclick> [英] Get Clicked <li> from <ul onclick>

查看:133
本文介绍了获取点击< li>从< ul onclick>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

作为一个JS的相对初学者,我努力尝试找到解决方案。

 < ul onclick =alert(this.clicked.line.id);> 
< li id = l1>第1行< / li>
< li id = l2>第2行< / li>
< li id = l3>第3行< / li>
< / ul>

我并不想为每条线添加一个onclick事件,我确定那里必须是一种方式??您可以使用 event.target 为此:



JS:

  // IE不知道目标属性。它寻找srcElement 
//该函数将以浏览器兼容的方式获取事件目标
function getEventTarget(e){
e = e || window.event;
返回e.target || e.srcElement;
}

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

HTML:

 < ul id =test> 
< li>第1项< / li>
< li>第2项< / li>
< li>第3项< / li>
< / ul>

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



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


As a relative beginner with JS, I am struggling to try and find a solution to this.

I need to find out which line of an unordered list was clicked

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

I don't really want to add a onclick event to each individual line, I'm sure there must be a way ??

解决方案

You can use event.target for this:

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

HTML:

<ul id="test">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

Example: http://jsfiddle.net/ArondeParon/2dEFg/5/

Please note that this is a very basic example and you will likely encounter some problems when you delegate events to elements containing more than one level. When this happens, you will have to traverse the DOM tree upwards to find the containing element.

这篇关于获取点击&lt; li&gt;从&lt; ul onclick&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆