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

how to append an array inside a ul in javascript?(如何在javascript中的ul中附加一个数组?)
本文介绍了如何在javascript中的ul中附加一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将名为短语的数组附加到名为 addPhraseToDisplay() 的方法时遇到问题.这是数组:

I am having trouble appending an array called phrases to a method called addPhraseToDisplay(). Here is the array:

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);,但这不起作用

what I want to do is append the array into as list items, I tried to target the phrases like this newListItem.textContent = (this.phrases);, but that didn't work

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 代码,我希望将数组作为列表项放入其中

this is html code where I would like the array to be inside as list items

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

            </ul>

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

if someone could help I would appreciated

推荐答案

<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 循环示例.

Previous example with for loop.

这篇关于如何在javascript中的ul中附加一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)