附加到 JavaScript 中的列表

Appending to a list in javascript

本文关键字:列表 JavaScript      更新时间:2023-09-26

当尝试附加到我的列表时,它只是不断将其添加到同一列表项的末尾。这是我的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();
    }
}