简体   繁体   English

JavaScript中的有序列表迭代

[英]Ordered List Iteration in Javascript

Is there a way to allow me to iterate through an ordered list similar in functionality as table.rows? 有没有一种方法可以让我遍历功能类似于table.rows的有序列表? I am using Javascript. 我正在使用Javascript。

The reason I ask this is because I have an ordered list that contains another ordered list inside. 我之所以这样问,是因为我有一个有序列表,其中包含另一个有序列表。 I just want to return the parent list items and not the child. 我只想返回父项列表项而不是子项。

<ol id="pList">
    <li>Item A</li>
    <li>
        <ol id="cList">
            <li>A's Child 1</li>
            <li>A's Child 2</li>
        </ol>
    </li>
    <li>Item B</li>
    <li>Item C</li>
    <li>Item D</li>
</ol>

I now use getElementsbyTag and that returns all li's including the one in cList. 我现在使用getElementsbyTag,它返回所有li,包括cList中的那个。 I just want the ones in pList. 我只想要pList中的那些。

Thanks 谢谢

FYI: I would prefer it done in Javascript. 仅供参考:我更喜欢用Javascript完成。 The code has to work within Greasemonkey. 该代码必须在Greasemonkey中起作用。 I don't really know much about jquery and I am not really much of a javascript programmer. 我对jquery的了解不多,也不是一个JavaScript程序员。

There is no specific property that gives you direct access to the <li> children of an <ol> . 没有特定的属性可让您直接访问<ol><li>子级。

However it is very easy to enumerate them, particularly when you consider that the only legal children of an <ol> must be white space text nodes and <li> nodes. 但是,枚举它们非常容易,特别是当您考虑<ol>的唯一合法子代必须是空白文本节点和<li>节点时。

var ol = document.getElementById('pList');
var li = [];
var node = ol.firstChild;
while (node) {
    if (node.tagType === 3 && node.tagName === 'LI') {
        li.push(node);
    }
    node = node.nextSibling;
}

At the end of which, the array li contains the required children. 最后,数组li包含必需的子级。

The above code will work in any browser. 上面的代码将在任何浏览器中运行。 The .children collection has problems on older versions of MSIE, and querySelectorAll is even more modern (and therefore less widely supported). .children集合在旧版本的MSIE上存在问题,而querySelectorAll甚至更现代(因此,得到的支持范围更小)。

If using querySelectorAll() * is an option for you, it's easy: 如果使用querySelectorAll() *为您提供一个选项,则很简单:

var listItems = document.querySelectorAll( '#pList > li' );

* note: it's a native DOM method, and has nothing to do with jQuery * 注意:这是本机DOM方法,与jQuery无关

There's a table of immediate children in every javascript object : 每个javascript对象中都有一张直接子表:

document.getElementById('pList').children

You can even iterate through it and check whatever your need : 您甚至可以遍历它并检查您的需要:

var el = document.getElementById('pList');
for (var i = 0; i < el.children.length; i++) {
    if (el.children[i].tagName == "LI") {
        el.children[i].doWhatever();
    }
}

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

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