Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

javascript - Get Clicked <li> from <ul onclick>

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...