我有一个关键字列表,我想基于<li id="newKeyword">
过滤:
<ul id="keywordList">
<li></li>
<li id="newKeyword"></li>
<li></li>
<li></li>
<li></li>
</ul>
当我点击一个按钮时,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
。