admin管理员组文章数量:1336115
First of all I'm adding an EventListener to the ul, as follows:
action_list_ul.addEventListener("click", set_ua_value, false);
The set_ua_value job is to:
• Listen to every click made on the ul childs (li elements) • get the value (innerHTML?) of the a tag inside the clicked li
<ul id="action-list">
<li><a href="#">foo</a></li>
<li><a href="#">bar</a></li>
</ul>
In case foo was clicked on, I need to retrieve the "foo" string.
Since I'm fairly new to javascript, I'm not sure how to get the actual "this" of the clicked li.
I do not want to use jQuery. Thanks :)
First of all I'm adding an EventListener to the ul, as follows:
action_list_ul.addEventListener("click", set_ua_value, false);
The set_ua_value job is to:
• Listen to every click made on the ul childs (li elements) • get the value (innerHTML?) of the a tag inside the clicked li
<ul id="action-list">
<li><a href="#">foo</a></li>
<li><a href="#">bar</a></li>
</ul>
In case foo was clicked on, I need to retrieve the "foo" string.
Since I'm fairly new to javascript, I'm not sure how to get the actual "this" of the clicked li.
I do not want to use jQuery. Thanks :)
Share asked Jul 30, 2013 at 23:38 elad.chenelad.chen 2,4356 gold badges27 silver badges39 bronze badges 1- Even when I think about it, I'm still not sure how the actual instance will be passed into the function.. – elad.chen Commented Jul 30, 2013 at 23:43
3 Answers
Reset to default 5A quick and dirty way is to bind the event to the list, and filter by anchor tags:
JS
var action_list_ul = document.getElementById('action-list');
action_list_ul.addEventListener("click", set_ua_value, false);
function set_ua_value (e) {
if(e.target.nodeName == "A") {
console.log(e.target.innerHTML);
}
}
JS Bin
Alternately, you can filter by LI
, and access the anchor through firstChild
or childNodes[0]
.
Use something like:
var win = window, doc = document, bod = doc.getElementsByTagName('body')[0];
function E(e){
return doc.getElementById(e);
}
function actionListValue(element, func){
var cn = element.childNodes;
for(var i=0,l=cn.length; i<l; i++){
if(cn[i].nodeType === 1){
var nc = cn[i].childNodes;
for(var n=0,c=nc.length; n<c; n++){
if(nc[n].nodeType === 1){
nc[n].onclick = function(){
func(this.innerHTML);
}
}
}
}
}
}
actionListValue(E('action-list'), set_ua_value);
Here is an alternative:
var foo = document.getElementById("foo");
foo.addEventListener("click", modifyText);
function modifyText(e) {
console.log(e.target.innerHTML);
}
In this case the binding would have to be with the a
elements.
<ul id="action-list">
<li><a href="#" id="foo">foo</a></li>
<li><a href="#" id="bar">bar</a></li>
</ul>
JS BIN
本文标签: javascriptGetting the value of the clicked li elementStack Overflow
版权声明:本文标题:javascript - Getting the value of the clicked li element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742403233a2468304.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论