当尝试附加到我的列表时,它只是不断地将其添加到同一列表项的末尾。这是我的js:
var title = document.createElement("h1");
var subTitle = document.createElement("h3");
var img = document.createElement("img");
var list = document.createElement("li");
var btn = document.createElement("button");
var myDiv = document.getElementById("container");
var myList = document.getElementById("pokemon");
var keepGoing = true;
function pokemonList(){
var theList = prompt("Enter one of your favorite pokemon");
list.textContent = theList;
myList.appendChild(list);
keepGoing = confirm("Would you like to add another pokemon?");
if(keepGoing)
pokemonList();
}
<body>
<div id = "container"></div>
<ol id="pokemon"></ol>
<script src="pageGenerator.js" type="text/javascript"></script>
<script>myPage();</script>
<script>pokemonList();</script>
</body>
编辑:第一个问题已修复,但现在每次我输入新的神奇宝贝时,第一个元素都会被替换。
最佳答案
createTextNode
只是添加文本,它不会创建新的 li
。试试这个:
function pokemonList(){
var theList = prompt("Enter one of your favorite pokemon");
var node = document.createElement('li');
node.textContent = theList;
document.getElementById('pokemon').appendChild(node);
var keepGoing = confirm("Would you like to add another pokemon?");
if(keepGoing) {
pokemonList();
}
}
关于javascript - 在 javascript 中追加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35584966/