将数组追加到无序列表
我试图用这段代码完成的是将数组 alphabet
作为一系列列表项输出到实际标记中的现有无序列表中。我已将数组放入列表项中,但我不知道如何告诉它将自身附加到现有的无序列表
。
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!");
}
What I'm trying to accomplish with this code is to output the array alphabet
as a series of list items into an existing unordered list in the actual markup. I've got the array into list items, but I can't figure out how to tell it to append itself to an existing unordered list <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!");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用
document.write
来执行此操作。你应该这样做:更正确的方法是使用 DOM(如果你想完全控制即将发生的事情):
Don't use
document.write
to do it. You should act like this:More proper way is to use DOM (in case you want full control of what's coming on):
您可以结合使用createElement() 和appendChild() 在另一个HTML 元素中添加新的HTML 元素。下面的代码应该适合您:
注意脚本如何存在于 body 标记下方。如果您希望脚本按照您编写的方式工作,这一点很重要。否则 document.getElementById('itemList') 将找不到 'itemList' ID。
You can use a combination of createElement() and appendChild() to add new HTML elements within another HTML element. The code below should work for you:
Note how the script exists below the body tag. This is important if you want your script to work the way you wrote it. Otherwise document.getElementById('itemList') will not find the 'itemList' ID.
尽量减少对 DOM 的操作。
unorderedList
上的每个appendChild 都会强制浏览器重新渲染整个页面。使用 documentFragement 进行此类操作。因此,只有一个 DOM 操作会强制完全重绘,而不是
alphabet.length
重绘Try to reduce the actions on the DOM as much as possible. Every appendChild on
unorderedList
forces the browser to re-render the complete page. Use documentFragement for that sort of action.So there will be only one DOM action which forces a complete redraw instead of
alphabet.length
redraws