javascript - 在将项目推送到 HTML 元素后,我们如何刷新显示在 HTML 元素中的数组?

标签 javascript arrays

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

我的问题:一旦通过按钮对数组“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>

最佳答案

您可以创建一个新方法来更新 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>");
}

关于javascript - 在将项目推送到 HTML 元素后,我们如何刷新显示在 HTML 元素中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47320043/

相关文章:

javascript - 通过年龄验证来验证 dob

javascript - 对期望为 'number | string | undefined' 的属性使用泛型类型值

ios - 将数组中的特定对象保存到新数组中

php - 如何将多个可重复字段保存为数据库中的数组?

java - 递归表/行生成器

c# - 从字符数组中删除一个字母

c - 防止数组写入不存在的索引

javascript - 用 jquery 交换图像并显示缩放图像

javascript - 如何获取特定 ul 的选中复选框

javascript - 为什么我的 setTimeout 函数在延迟时使用 jquery 的 ReplaceWith() 来淡出、替换和淡入文本不起作用?