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
Add a ment  | 

3 Answers 3

Reset to default 5

A 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