将数组附加到无序列表

时间:2010-08-26 15:07:09

标签: javascript arrays markup

我想用这段代码完成的工作是将数组alphabet作为一系列列表项输出到实际标记中的现有无序列表中。我已将数组放入列表项,但我无法弄清楚如何告诉它将自己附加到现有的无序列表<ul id="itemList"></ul>

var itemsExist = true;
var indexNum = 0;
var unorderedList = document.getElementById('itemList');
var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");

function write_letters(){

    for (i = 0; i < alphabet.length; i++ ) {
        document.write('<li>'  + alphabet[indexNum++] + '</li>');
    }

}

if (itemsExist){
    write_letters();
} else {
    document.write("error!");
}

3 个答案:

答案 0 :(得分:8)

请勿使用document.write来执行此操作。你应该这样做:

function write_letters(){
    var letters = "";

    for (var i = 0; i < alphabet.length; i++ ) {
        //Also I don't understand the purpose of the indexNum variable.
        //letters += "<li>"  + alphabet[indexNum++] + "</li>";
        letters += "<li>"  + alphabet[i] + "</li>";
    }

    document.getElementById("itemList").innerHTML = letters;
}

更正确的方法是使用DOM(如果你想完全控制正在发生的事情):

function write_letters(){
    var items = document.getElementById("itemList");

    for (var i = 0; i < alphabet.length; i++ ) {
        var item = document.createElement("li");
        item.innerHTML = alphabet[i];
        items.appendChild(item);
    }

}

答案 1 :(得分:2)

您可以使用createElement()和appendChild()的组合在另一个HTML元素中添加新的HTML元素。以下代码适合您:

<html>

<head>
<title>Script Test</title>
</head>

<body>
    <ul id="itemList"></ul>
</body>

<script>
    var itemsExist = true;
    var indexNum = 0;
    var unorderedList = document.getElementById('itemList');
    var alphabet= new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
    var myElement;

    function write_letters(){

        for (i = 0; i < alphabet.length; i++ ) {
            // Create the <LI> element
            myElement = document.createElement("LI");
            // Add the letter between the <LI> tags
            myElement.innerHTML = alphabet[indexNum++];
            // Append the <LI> to the bottom of the <UL> element
            unorderedList.appendChild(myElement);
        }
    }

    if (itemsExist){
        write_letters();
    } else {
        document.write("error!");
    }
</script>

</html>

请注意脚本如何存在于body标记下方。如果您希望脚本以您编写的方式工作,这一点很重要。否则document.getElementById('itemList')将找不到'itemList'ID。

答案 2 :(得分:2)

尝试尽可能减少对DOM的操作。 unorderedList上的每个appendChild都会强制浏览器重新呈现整个页面。使用documentFragement进行此类操作。

var frag = document.createDocumentFragment();
for (var i = alphabet.length; i--; ) {
   var li = document.createElement("li");
   li.appendChild(document.createTextNode(alphabet[indexNum++]));
   frag.appendChild(li);
}
unorderedList.appendChild(frag);

因此,只有一个DOM动作强制完全重绘而不是alphabet.length重绘