简体   繁体   中英

how get access to children in javascript?

i am using jquery in my code and i have a list and when i call my function to access text element in my code undefined is back.

this is my code

xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var place_obj = JSON.parse(this.responseText);
    for (var k = 0; k < Object.keys(place_obj).length; k++) {
      if (k % 2 == 0) {
        document.getElementById('dropdownplace').innerHTML +=
          '<a class="dropdown-item font_size_x1" style="background-color:#d9d9d947" ' +
          'href="#" onclick="pFilter()" id="' + k + '"><span class="">- </span>' + place_obj[k].Type + '</a>';
      } else {
        document.getElementById('dropdownplace').innerHTML +=
          '<a class="dropdown-item font_size_x1" ' +
          'href="#" onclick="pFilter()" id="' + k + '"><span>- </span>' + place_obj[k].Type + '</a>';
      }
    }
  }
};

function pFilter() {
  var place = document.getElementById('1').value;
  console.log(place) //undefiend 
}

I assume you want to select clicked element text . You don't need id basically, you can call current clicked element by event.target . I created mock json instead of xmlhttp response ....

 var place_obj = [{Type: 'a'},{Type: 'b'}]; for (var k = 0; k < Object.keys(place_obj).length; k++) { if (k % 2 == 0) { document.getElementById('dropdownplace').innerHTML += '<a class="dropdown-item font_size_x1" style="background-color:#d9d9d947" ' + 'href="#" onclick="pFilter()"><span class="">- </span>' + place_obj[k].Type + '</a>'; } else { document.getElementById('dropdownplace').innerHTML += '<a class="dropdown-item font_size_x1" ' + 'href="#" onclick="pFilter()"><span>- </span>' + place_obj[k].Type + '</a>'; } } function pFilter() { console.log(event.target.textContent); } 
 <div id="dropdownplace"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM