简体   繁体   English

使用Javascript遍历无序列表

[英]Loop through an unordered list using Javascript

I'm having a bit of a struggle to loop through an unordered list, that is produced by kendo-ui. 我正在努力浏览由kendo-ui生成的无序列表。 Looking at its markup, it looks like this: 查看其标记,它看起来像这样:

<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]. 我可以从列表中删除所有行,但是我从中得到的只是它们的索引号,在这种情况下为[0,...,6]。 What I really need is to fetch the id-part signalRconveyanceId-XXYY for each list element. 我真正需要的是为每个列表元素获取id部分signalRconveyanceId-XXYY How would I be able to do that? 我该怎么做?

Try to use jquery attr() like, 尝试使用jatt attr()之类的方法,

var listItems = $("#unitlist li");
listItems.each(function(li) {
    console.log($(this).attr('id'));
});

As your HTML shown you should select list item like 您的HTML所示,您应该选择列表项,例如

 var listItems = $("#unitlist li ul li");

Updated 更新

var listItems = $("#unitlist li ul li");
listItems.each(function(index,li) {
    console.log(li.id);
});

Updated fiddle 更新的小提琴

In your code li is not actually the element - it's the index. 在您的代码中, li实际上不是元素-它是索引。 You can refer to each of the li elements using this ... 您可以使用this ...引用每个li元素。

var listItems = $("#unitlist li");
listItems.each(function() {
    console.log(this.id);
});

I got this: 我懂了:

 var listItems = $("#unitlist li");
   listItems.each(function(li) {
   $id = $(this).attr('id');
   console.log($id);
 });

http://jsfiddle.net/lharby/cTEHY/ http://jsfiddle.net/lharby/cTEHY/

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

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