Javascript 如何将for循环的值添加到<;李>;设计它的风格? var myArray=['hi','hi there','hi there','sup']; var myList=document.getElementById('list');//我有一个li,id为list 函数hello(){ 对于(var i=0;i
我不熟悉javascript:)您不应该使用Javascript 如何将for循环的值添加到<;李>;设计它的风格? var myArray=['hi','hi there','hi there','sup']; var myList=document.getElementById('list');//我有一个li,id为list 函数hello(){ 对于(var i=0;i,javascript,Javascript,我不熟悉javascript:)您不应该使用document.write(),因为这只在加载页面时起作用,被认为是不好的做法。您应该在列表的.innerHTML属性上使用+= a+=b运算符是a=a+b的缩写 它将b附加到a的当前值,您在循环中运行它,因此它每次都会添加 HTML Javascript var myArray=['hi','hi there','hi there','sup']; var content=document.getElementById('content');
document.write()
,因为这只在加载页面时起作用,被认为是不好的做法。您应该在列表的.innerHTML
属性上使用+=
a+=b
运算符是a=a+b
的缩写
它将b
附加到a
的当前值,您在循环中运行它,因此它每次都会添加
HTML
Javascript
var myArray=['hi','hi there','hi there','sup'];
var content=document.getElementById('content');
对于(var i=0;i”+myArray[i]+“”)
}
代码演示:在这里,尝试以下操作:
var myArray = ['hi' , 'hi there' , 'hi there again' , 'sup'];
var content = document.getElementById('content');
for (var i = 0; i < myArray.length; i++) {
ul.innerHTML += ('<li>'+myArray[i] + '</li>')
}
var myArray=['hi','hi there','hi there','sup'];
var myList=document.getElementById('list').parentNode;
函数hello(){
对于(var i=0;i'+myArray[i]+'';
}
你好;
这将产生以下结果:
var myArray = ['hi' , 'hi there' , 'hi there again' , 'sup'];
var myList = document.getElementById('list').parentNode;
function hello(){
for (var i = 0; i < myArray.length; i++)
myList.innerHTML+='<li class="list">'+myArray[i]+'</li>';
}
hello();
- 嗨
你好
...
阅读更多关于和的信息。将列表的
innerHTML
属性设置为包含写入内容的“li”标记字符串可能是最简单的方法,如下所示:
var html='';
对于(var i=0;i'+myArray[i]+''
}
document.getElementById('list')。innerHTML=html代码>使用纯DOM方法
<ul>
<li id='list'></li> <!-- As mentioned in the question -->
<li class='list'>hi</li>
<li class='list'>hi there</li>
...
</ul>
var myArray=['hi','hi there','hi there','sup'];
var myList=document.getElementById('list');//我有一个li,id为list
函数hello(){
对于(var i=0;i
您需要编辑您的问题,您想将其添加到哪里,添加到什么元素?您需要查看Javascript中的dom操作。
我想将其添加到此liSo中,您想将数组中元素的id
插入列表元素中吗?与此类似,正确阅读问题和对问题的评论。最佳答案+1、最少代码和对javascript框架的引用。“li”的Id必须是“list”,而不是“ul”标记。这将是对HTML的错误使用。您只能将标记放在中。页面上不能有多个同名ID。这将无法验证,并且是不正确的HTML。您是对的。但是因为他想要它…我从来没有检查过。不管怎样,我会把它改成课堂。
var myArray = ['hi' , 'hi there' , 'hi there again' , 'sup'];
var myList = document.getElementById('list').parentNode;
function hello(){
for (var i = 0; i < myArray.length; i++)
myList.innerHTML+='<li class="list">'+myArray[i]+'</li>';
}
hello();
<ul>
<li id='list'></li> <!-- As mentioned in the question -->
<li class='list'>hi</li>
<li class='list'>hi there</li>
...
</ul>
var myArray = ['hi', 'hi there', 'hi there again', 'sup'];
var myList = document.getElementById('list'); // i have an li with an id of list
function hello() {
for (var i = 0; i < myArray.length; i++) {
var listItem = document.createElement("li");
listItem.appendChild(document.createTextNode(myArray[i]));
myList.appendChild(listItem);
}
};
hello();