繁体   English   中英

为什么jQuery attr返回undefined而不是'href'?

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

我正在尝试使用jQuery attr('id')从li元素获取ID,但是即使返回的确是attr('href')的正确值,它也会返回未定义的值。 我很沮丧 这是我的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;
  })

代替

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

尝试

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

event.target是链接,并且没有id 您需要从父母那里得到它:

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

首先,您需要使用jQuery .each()函数来定位每个单独的元素。 然后,您可以使用“此”选择器来定位点击的元素。 最后,要定位到锚点,您需要使用jQuery .find()函数找到单击的li的子元素。 这样,您应该可以和朋友一起去! Codepen

经检查和测试的jQuery代码:

$('#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;
  });
});

您应该使用jQuery每个函数。 然后,您应该使用item作为参数,而不是使用引用,您可以通过参数将其视为HTMLLIElement

要使用.attr您需要传递data-attribute例如data-id="something" 尝试使用.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;
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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