簡體   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