简体   繁体   中英

Why is jQuery attr returning undefined for 'id' but not 'href'?

I am trying to get the id from li elements using jQuery attr('id'), but it is returning undefined even though it does return what appears to be the correct values for attr('href'). I'm stumped. Here's a link to my Codepen

  <ul id="sortList">
  <li id="one"><a href='#'>Ratings</a></li>
  <li id="2"><a href=#>Reviews</a></li>
  <li id="3"><a href=#>Type</a></li>
  </ul>
  <h2 id="anchorInfo">hello</h2>
  <h2 id="clickInfo">hello</h2>


  $('#sortList li').click( function(event){
  event.preventDefault();
  let whatHref = $(event.target).attr('href');
  let whatId = $(event.target).attr('id');
  document.getElementById('anchorInfo').innerHTML = whatHref;
  document.getElementById('clickInfo').innerHTML = whatId;
  })

Instead of

  $(event.target).attr('id');

try

  $(this).attr('id');

The event.target is the link, and that doesn't have an id . You need to get it from the parent:

$(event.target).parent().attr('id')

First you need to target each of the individual elements using the jQuery .each() function. You will then be able to target the clicked elements by using the 'this' selector. Finally to target the anchor you need to find the child element of the clicked li by using the jQuery .find() function. You should then be good to go by friend! Codepen

Reviewed and tested jQuery code:

$('#sortList li').each(function(){
  $(this).click(  function(event){
    event.preventDefault();
    let whatHref = $(this).find('a').attr('href');
    let whatId = $(this).attr('id');
    document.getElementById('anchorInfo').innerHTML   = whatHref;
    document.getElementById('clickInfo').innerHTML   = whatId;
  });
});

You should use jQuery each function. Then, instead of using this reference, you should use item as parameter from which you may do things treating it as HTMLLIElement .

To use .attr you need pass a data-attribute like data-id="something" . Try use .prop()

  <ul id="sortList">
  <li id="one"><a href='#'>Ratings</a></li>
  <li id="2"><a href=#>Reviews</a></li>
  <li id="3"><a href=#>Type</a></li>
  </ul>
  <h2 id="anchorInfo">hello</h2>
  <h2 id="clickInfo">hello</h2>


  $('#sortList li').click( function(event){
  event.preventDefault();
  let whatHref = $(event.target).prop('href');
  let whatId = $(event.target).prop('id');
  document.getElementById('anchorInfo').innerHTML = whatHref;
  document.getElementById('clickInfo').innerHTML = whatId;
  })

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