【问题标题】:loop through an array and add every object to ul as an li循环遍历数组并将每个对象作为 li 添加到 ul
【发布时间】:2018-01-28 04:06:29
【问题描述】:

我的最终目标是让它向 ul 吐出一个口袋妖怪名称列表。我可以让它们出现在控制台上,但仍然是一个数组。 这是我的html

<div id="pokeList">
 <ul>
  <li></li>
 </ul>
</div>

下面是我的javascript。

pokeHTML() {
    var pokemonList = "";
    for (var i = 0; i < this.pokemonList.length; i++) {
        // console.log(this.pokemonList[i]);
        $("#pokeList ul").append('<li>' + this.pokemonList[i] + '</li>');
    }
    return pokemonList;
}

【问题讨论】:

  • 您的代码可以工作,您只需将pokemonList 设为一个字符串数组。目前它只是一个字符串,所以你正在遍历每个字符。

标签: javascript jquery html arrays


【解决方案1】:

在这种情况下你不需要使用“this” 在您的函数中,“this”指的是窗口对象,而不是您的 javascript 函数。

所以你必须删除“this”或将“pokemonList”设为全局变量(删除“var”)

【讨论】:

    【解决方案2】:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="pokeList">
        <ul>
        </ul>
    </div>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        $(function () {
            let pokemonList = ['a', 'b', 'c', 'd'];
            for (let i = 0; i < pokemonList.length; i++) {
                $("#pokeList ul").append(`<li>${pokemonList[i]}</li>`);
            }
        });
    </script>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2015-05-14
      • 2019-06-29
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多