【问题标题】:How do I put unordered list items into an array如何将无序列表项放入数组
【发布时间】:2010-05-08 10:24:51
【问题描述】:

我的代码是...

如何使用原生 javascript 将每个列表项中的文本放入数组中?

<ul id="list">
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
    <li>List Item 4</li>
</ul>

<script type="text/javascript">
var list = document.getElementById('list').childNodes.TextNode;
for(var i=0;i < list.length; i++) {
    var arrValue = list[i];
    alert(arrValue);
}
</script>

非常感谢。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    除非您想要每个 &lt;li&gt; 之间的文本节点,否则使用 childNodes 不是一个好主意。 getElementsByTagName('li') 怎么了?

    var listItems = document.getElementById('list').getElementsByTagName('li'),
    
        myArray = map(listItems, getText);
    
    function map(arrayLike, fn) {
        var ret = [], i = -1, len = arrayLike.length;
        while (++i < len) ret[i] = fn(arrayLike[i]);
        return ret;
    }
    
    function getText(node) {
        if (node.nodeType === 3) return node.data;
        var txt = '';
        if (node = node.firstChild) do {
            txt += getText(node);
        } while (node = node.nextSibling);
        return txt;
    }
    

    【讨论】:

    • 目前为止最好的,尽管如果存在嵌套列表将是一个问题,因为getElementsByTagName 当然是分层的。不过,为什么不只是 map(listItems, getText)
    • @bibince,改为map(listItems, getText)。谢谢!
    【解决方案2】:

    试试这个:

    var list = document.getElementById('list').childNodes;
    var theArray = [];
    for(var i=0;i < list.length; i++) {
        var arrValue = list[i].innerHTML;
        alert(arrValue);
        theArray.push(arrValue);
    }
    

    【讨论】:

    • childNodes 包含空白文本节点,innerHTML 未定义。 innerHTML 将为某些文本返回转义字符。
    【解决方案3】:

    几乎任何Javascript libraryPrototypejQueryClosure,...)都会让这更容易,但如果你想自己做:

    你已经接近了,你的 Javascript 应该看起来像这样:

    window.onload = onPageLoad; // Or any of several other similar mechanisms
                                // (you could just run it at the bottom of the page)
    function onPageLoad() {
        var node, list, arrValue;
    
        list = [];
        for (node = document.getElementById('list').firstChild;
            node;
            node = node.nextSibling) {
            if (node.nodeType == 1 && node.tagName == 'LI') {
                list.push(node.innerHTML);
            }
        }
    
        // `list` now contains the HTML of each LI element under the `ul#list` element
    }
    

    解释:

    • 在使用document.getElementById 之前,您需要确保DOM 已准备好执行此操作。它肯定在onload 时间准备就绪,如果您愿意,有多种机制可以提前触发您的代码(包括将脚本放在最后)。
    • 循环首先获取 ul#list 元素的第一个子元素,然后只要还有其他兄弟元素就继续。
    • 在循环中,我们检查每个节点是一个元素 (nodeType == 1) 并且它的标签名称是“LI”。
    • 如果是,我们检索其 HTML 并将其推送到数组中。

    我使用innerHTML 来检索 LI 的内容,因为它得到了广泛的支持。或者,您可以在 IE(和其他一些)上使用 innerText,在 Firefox 上使用 textContent,但要注意它们不会完全做同样的事情(Firefox 上的textContent 将包括script 标签的内容,例如,这可能不是你想要的)。

    【讨论】:

    • @J-P:这当然是一种选择;无论哪种方式,它都是一个循环,使用getElementsByTagName 需要第二次函数调用并创建一个NodeList,如果你无论如何都要循环,这似乎是不必要的。 (那是你的否决票吗?如果是这样,只是因为采取不同的方式似乎有点苛刻......)
    【解决方案4】:
    var LIs = document.getElementById('list').childNodes;
    var list = [];
    for( var i = 0; i < LIs.length; ++i )
    {
        var LI = LIs[i];
        list.push(LI.innerText || LI.textContent);
    }
    

    和往常一样,使用 jQuery 的更简单方法:

    var list = $('#list li').map(function(){ return $(this).text(); });
    

    【讨论】:

    • childNodes 包含列表中不需要的空白文本节点(并且未定义 innerText)。 || 空字符串 innerText 测试失败,让 IE 将 undefined 放入数组中。
    • 有了 jQuery,它甚至更简单:var list = $('#list li').map(function(){return $.text([this])});
    【解决方案5】:

    var list = document.getElementsByTagName('ul')[0].getElementsByTagName('li');

    var theArray = [];
    
    for (var i = 0; i < list.length; i++) {
        var arrValue = list[i].innerHTML;
        console.log(arrValue);
        theArray.push(arrValue);
    }
    

    【讨论】:

    • nickf 的回答基本上是使用 getElementsByTagName 而不是使用子节点
    猜你喜欢
    • 2020-06-27
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    相关资源
    最近更新 更多