Как добавить массив внутри UL в JavaScript? - PullRequest
0 голосов
/ 30 ноября 2018

У меня возникли проблемы с добавлением массива phrases в метод 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 голосов
/ 10 декабря 2018
<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.

0 голосов
/ 30 ноября 2018

Здравствуйте, вы можете попробовать это:

<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>

Надеюсь, это именно то, что вы ищете.

...