Javascript创建li并附加到ol
我正在尝试使用JavaScript创建一个li并将其附加到现有的ol。我使用的代码是Javascript创建li并附加到ol,javascript,html-lists,Javascript,Html Lists,我正在尝试使用JavaScript创建一个li并将其附加到现有的ol。我使用的代码是 <ol id=summaryOL> </ol> function change(txt) { var x=document.getElementById("summaryOL"); newLI = document.createElementNS(null,"li"); newText = document.createTextNode(txt); newLI.appendChild(
<ol id=summaryOL>
</ol>
function change(txt) {
var x=document.getElementById("summaryOL");
newLI = document.createElementNS(null,"li");
newText = document.createTextNode(txt);
newLI.appendChild(newText);
x.appendChild(newLI);
}
change("this is the first change");
change("this is the second change");
但是看起来:
1. this is ...
2. this is ...
this is the first changethis is the second change
我在:。谢谢您的帮助。您的小提琴与您的问题无关 在你的小提琴中,它工作得很好,但你永远不应该有一个以数字开头的ID
在你的问题中,
createElements
是毫无意义的-只需使用createElement('li')
。你的小提琴与你的问题无关
在你的小提琴中,它工作得很好,但你永远不应该有一个以数字开头的ID
在您的问题中,createElements
是毫无意义的-只需使用createElement('li')
。这里是-jsfiddle
$(function() {
var change = function( txt ) {
$("#summaryOL").append( '<li>' + txt + '</li>' );
};
change("this is the first change");
change("this is the second change");
});
$(函数(){
变量更改=函数(txt){
$(“#summaryOL”).append(“”+txt+” ”);
};
变更(“这是第一次变更”);
变更(“这是第二次变更”);
});
要使用jquery,请将下面的代码放在
这里是-jsfiddle
$(function() {
var change = function( txt ) {
$("#summaryOL").append( '<li>' + txt + '</li>' );
};
change("this is the first change");
change("this is the second change");
});
$(函数(){
变量更改=函数(txt){
$(“#summaryOL”).append(“”+txt+” ”);
};
变更(“这是第一次变更”);
变更(“这是第二次变更”);
});
要使用jquery,请将下面的代码放在
试试下面。这对我有用。从中删除空值
试试下面。这对我有用。从中删除空值
如果您正在使用jQuery,可以尝试以下方法:
var item= "<li>" + "some info" + "</li>" ;
$("#items").html($("#items").html() + var);
var item=“”+“一些信息”+“ ”;
$(“#items”).html($(“#items”).html()+var);
显然,附加到列表中是另一种解决方案。如果您使用的是jQuery,您可以尝试以下方法:
var item= "<li>" + "some info" + "</li>" ;
$("#items").html($("#items").html() + var);
var item=“”+“一些信息”+“ ”;
$(“#items”).html($(“#items”).html()+var);
显然,添加到列表中是另一种解决方案。只是看看这个,我不相信没有jQuery它就没有答案,所以把它放在这里。在Vanilla JS中,您可以执行以下操作:
const ol = document.querySelector("#summaryOL");
const li = document.createElement('li');
const text = document.createTextNode(txt);
li.appendChild(text);
ol.appendChild(li);
或者,通过直接修改ol
节点的innerHTML
:
document.querySelector('#summaryOL').innerHTML =
changes
.map(txt => `<li>${txt}</li>`)
.join('');
document.querySelector('#summaryOL').innerHTML=
变化
.map(txt=>`${txt} `)
.加入(“”);
只是看看这个,不敢相信没有jQuery它还没有被回答,所以把它放在这里。在Vanilla JS中,您可以执行以下操作:
const ol = document.querySelector("#summaryOL");
const li = document.createElement('li');
const text = document.createTextNode(txt);
li.appendChild(text);
ol.appendChild(li);
或者,通过直接修改ol
节点的innerHTML
:
document.querySelector('#summaryOL').innerHTML =
changes
.map(txt => `<li>${txt}</li>`)
.join('');
document.querySelector('#summaryOL').innerHTML=
变化
.map(txt=>`${txt} `)
.加入(“”);
ID属性值以数字开头完全可以。看,ID属性值以数字开头是很好的。参见。答案不应依赖于OP中未提及或标记的库。答案不应依赖于OP中未提及或标记的库。