【问题标题】:How can we refresh an array displayed in an HTML element after an item is pushed to it?在将项目推送到 HTML 元素中后,我们如何刷新显示在 HTML 元素中的数组?
【发布时间】:2017-11-16 01:24:29
【问题描述】:

这个文件是一个简单的列表生成器。它从 JS 数组的 div 中显示的三个示例项目开始。 onclick 按钮一个“推”出现提示,用户添加的任何内容都会添加到 JS 中的数组中。根据控制台,这可以正常工作。第二个按钮“shift”将第一项从列表中拉出(传统的做列表样式),因为用户一次做一个项目。push 和 shift 按钮都运行相应的 JS 函数,可以完美地完成工作。在控制台中,每次使用 wither 时都会更新数组。

我的问题:一旦通过按钮对数组“toDoList”进行了修改,我如何让 div 刷新数组“toDoListJoined”???

 <!DOCTYPE html>
 <html lang="en">

 <head>
 <meta charset="utf-8" />
 <title>JavaScript To Do List</title>
 </head>


 <body id="home">
   <button id="push" onclick="pushPrompt()">Add something to the end of your list</button>
   <button id="shift" onclick="shiftIt()">Remove the first item from your list</button>


 <p id="listPlace">
 <!--Here's where the magic happens-->
 </p>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <script type="text/javascript">
   let toDoList = ["sample item 1", "sample item 2", "sample item 3"];
   let toDoListJoined = toDoList.join("<br>");
   let addItem = "";

document.getElementById("listPlace").innerHTML = toDoListJoined;

function pushPrompt() {
  addItem = prompt("What is the item you want to add to your list?", "Sample item");
  toDoList.push(addItem);
}

function shiftIt() {
  toDoList.shift();
}
 </script>

 </body>

</html>

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    您可以创建一个新方法以便更新 html:

    //create a new method on the Array to push the item and update the HTML. 
    toDoList.pushAndUpdate= function(item) {
        //push the item into the array using the prototype push method.
        Array.prototype.push.call(this, item);
        //update the html of my element. 
        document.getElementById("listPlace").innerHTML= this.join("<br>");
    }
    

    【讨论】:

    • 这只是个坏建议。数组只是一个数组,你不应该把它伪装成一个类并覆盖它的原生属性。
    • 使用相同的想法声明一个名为pushAndUpdate的新方法会更好吗?
    • 那会更好,但如果我们做得好,我至少会创建一个对象,其中包含保存状态的方法和执行更新的函数。
    • 看看你的解决方案会很有趣。
    • 下面是我所说的示例:jsfiddle.net/DerekL/8oLjjsfc 当然,最好的方法是创建一个完整的Todos 类,但对于这个示例来说这有点过头了。
    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 2021-11-12
    • 2019-08-22
    相关资源
    最近更新 更多