如何在javascript中的ul中附加数组?

时间:2018-11-30 16:41:37

标签: javascript html arrays append

我在将名为短语的数组追加到名为addPhraseToDisplay()的方法时遇到麻烦。这是数组:

class Game {
constructor() {
    this.missed = 0; // this property will be used as a counter for the total of 5 tries
    this.phrases = ["life is strange","success does not come easy", "seven swans swimming", "guess the word", "wild goose chase"] 
}

我想做的是将数组追加到列表项中,我试图定位诸如newListItem.textContent = (this.phrases);这样的短语,但这没用

addPhraseToDisplay() {
   //Create a reference to ul element
    const myList = document.getElementById('myList');

    //Crete new list items
    let newListItem = document.createElement('li');
    newListItem.textContent = (this.phrases);

这是html代码,我希望将数组作为列表项放在其中

<!--My phrases need to be appended down here, div is parent element -->
        <div id="phrase" class="section">
            <ul id="myList">

            </ul>

如果有人可以帮助我,将不胜感激

2 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

<html>
<body>

<div id="myList">

</div>

<p>Click the button to append an item to the end of the list.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    //Creating element with html tag .... and append it to another element
    var node = document.createElement("UL");
    var textnode = document.createTextNode("Water");
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
}
</script>


</body>

希望它正是您想要的东西。

答案 1 :(得分:0)

<html>
<body>

<ul id="myList">

</ul>

<p>Click the button to append the array to the end of the list.</p>

<button onclick="myFunction()">Try it</button>

<script>
var myPhrases = ["Phrase 1", "Phrase 2", "Phrase 3", "Phrase 4", "Phrase 5"]
function myFunction() {
    //Creating element with html tag .... and append it to another element
    for (i = 0; i < myPhrases.length; i++)
    {
      var node = document.createElement("li");
      var textnode = document.createTextNode(myPhrases[i]);
      node.appendChild(textnode);
      document.getElementById("myList").appendChild(node);
    }
}

</script>


</body>

先前的for循环示例。