2016-02-23 34 views
0

當試圖追加到我的列表中時,它只是將它添加到同一列表項的末尾。這裏是我的JS:追加到javascript中的列表

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> 

編輯:第一個問題是固定的,但現在的第一個元素被替換每次我在一個新的口袋妖怪進入。

+0

請包括一個最小**完整的例子。您發佈的代碼缺少幾個關鍵部分(如創建「list」變量),導致無法運行。 – meagar

回答

2

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(); 
    } 
} 
+0

有了這個我的清單只是重置。每次我輸入新的內容時,都會替換第一個列表項。 –

+0

它對我來說工作正常https://jsfiddle.net/c4fxaqs7/ –

+0

是的,我得到它的工作謝謝你! –