And*_*ear 1 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(newText);
x.appendChild(newLI);
}
change("this is the first change");
change("this is the second change");
Run Code Online (Sandbox Code Playgroud)
这些应该是这样的:
1. this is ...
2. this is ...
Run Code Online (Sandbox Code Playgroud)
但看起来像:
this is the first changethis is the second change
Run Code Online (Sandbox Code Playgroud)
我创造了一个小提琴:小提琴.谢谢你的帮助.
这是一个例子 - jsfiddle
$(function() {
var change = function( txt ) {
$("#summaryOL").append( '<li>' + txt + '</li>' );
};
change("this is the first change");
change("this is the second change");
});
Run Code Online (Sandbox Code Playgroud)
要使用jquery,请将以下代码放在<head> </ head>中
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
只是看看这个,不敢相信没有 jQuery 就没有答案,所以就把它放在这里。在 Vanilla JS 中,你可以这样做:
const ol = document.querySelector("#summaryOL");
const li = document.createElement('li');
const text = document.createTextNode(txt);
li.appendChild(text);
ol.appendChild(li);
Run Code Online (Sandbox Code Playgroud)
或者,通过直接修改innerHTML节点ol:
document.querySelector('#summaryOL').innerHTML =
changes
.map(txt => `<li>${txt}</li>`)
.join('');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12754 次 |
| 最近记录: |