使用 Javascript 遍历无序列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19176692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through an unordered list using Javascript
提问by Nicklas Pouey-Winger
I'm having a bit of a struggle to loop through an unordered list, that is produced by kendo-ui. Looking at its markup, it looks like this:
我在遍历由 kendo-ui 生成的无序列表时遇到了一些困难。查看它的标记,它看起来像这样:
<ul data-role="listview" data-style="inset" data-type="group" id="unitlist">
<li>
<li>
<ul>
<li id="signalRconveyanceId-P32-HMU-01">
<a href="/UnitDetails/Index/1">P32-HMU-01
<span class="statusicon" style="background-color: #468847"></span>
</a>
</li>
<li id="signalRconveyanceId-P32-HMU-02">
<a href="/UnitDetails/Index/2">P32-HMU-02
<span class="statusicon" style="background-color: #b94a48"></span>
</a>
</li>
<li id="signalRconveyanceId-XOS-STAGING">
<a href="/UnitDetails/Index/3">XOS-STAGING
<span class="statusicon" style="background-color: #468847"></span>
</a>
</li>
<li id="signalRconveyanceId-NWI-100">
<a href="/UnitDetails/Index/4">NWI-100
<span class="statusicon" style="background-color: #"></span>
</a>
</li>
</ul>
</li>
</li>
</ul>
My javascript looks like this:
我的 javascript 看起来像这样:
var listItems = $("#unitlist li");
listItems.each(function(li) {
console.log(li);
});
I can get the rows out of the list allright, but all I get out of them is their index number, which in this case is [0, ..., 6].
What I really need is to fetch the id-part signalRconveyanceId-XXYY
for each list element. How would I be able to do that?
我可以从列表中取出行,但是我从它们中取出的只是它们的索引号,在这种情况下是 [0, ..., 6]。我真正需要的是获取signalRconveyanceId-XXYY
每个列表元素的 id 部分。我怎么能做到这一点?
回答by Rohan Kumar
Try to use jquery attr()like,
尝试使用jquery attr() 之类的,
var listItems = $("#unitlist li");
listItems.each(function(li) {
console.log($(this).attr('id'));
});
Asyour HTMLshown you should select list itemlike
正如您的HTML所示,您应该选择列表项,例如
var listItems = $("#unitlist li ul li");
Updated
更新
var listItems = $("#unitlist li ul li");
listItems.each(function(index,li) {
console.log(li.id);
});
回答by Reinstate Monica Cellio
In your code li
is not actually the element - it's the index. You can refer to each of the li
elements using this
...
在您的代码li
中实际上不是元素 - 它是索引。您可以li
使用this
...
var listItems = $("#unitlist li");
listItems.each(function() {
console.log(this.id);
});
回答by lharby
I got this:
我懂了:
var listItems = $("#unitlist li");
listItems.each(function(li) {
$id = $(this).attr('id');
console.log($id);
});