簡體   English   中英

如何在項目列表中查找具有 id 的列表項?

[英]How to find a list item with an id in a list of items?

我有一個要根據<li id="newKeyword">過濾的關鍵字列表:

<ul id="keywordList">
  <li></li>
  <li id="newKeyword"></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

當我單擊一個按鈕時,function showNewKeywords()觸發:

function showNewKeywords() {
  // Declare variables
  var ul, li;

  ul = document.getElementById("keywordList");
  li = ul.getElementsByTagName('li');


  // Loop through all list items, and hide those who don't have the li ID
  for (i = 0; i < li.length; i++) {

    // Find id of each li within the list
    
  }
}

我很難遍歷li標簽列表來找到帶有id的標簽。 我嘗試了getElementById方法,但它遍歷了整個文件(我認為)。

關於如何根據li id過濾li列表的任何提示?

非常感謝!

編輯:修正錯別字。

當你循環你需要獲取li元素時,我分配給a變量,並獲取它的id將它放在txtValue並測試它是否is not equal (!=)然后將其刪除並影響它的樣式display:none

 function showNewKeywords() { // Declare variables var ul, li; ul = document.getElementById("keywordList"); li = ul.getElementsByTagName('li'); // Loop through all list items, and hide those who don't have the li ID for (i = 0; i < li.length; i++) { //vvvv a = li[i]; // My main problem here //a = "find id of each li within the list"; txtValue = a.id; // This is a secondary problem but I'll figure it out if (txtValue.='newKeyword') { a.style;display = "none"; } } }
 <ul id="keywordList"> <li></li> <li id="newKeyword"></li> <li></li> <li></li> <li></li> </ul> <button onclick="showNewKeywords()">show New Keywords</button>

PS:選擇更好的變量命名:而不是a currentLI命名它更有意義,並且對於txtValue將其替換為idOfCurrLI

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM