gpt4 book ai didi

javascript - 将数组附加到无序列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:00:38 25 4
gpt4 key购买 nike

我试图用这段代码完成的是输出数组 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!");
}

最佳答案

不要使用 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);
}

}

关于javascript - 将数组附加到无序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3576482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com