【问题标题】:Delete array element by clicking button in HTML?通过单击 HTML 中的按钮删除数组元素?
【发布时间】:2019-10-01 22:28:12
【问题描述】:

我试图在 HTML 中创建一个删除按钮来删除数组中的一个元素,但为什么它不起作用? https://github.com/Clifford026/TodoList

 <script>
        function rem(value){
         todolist.splice(i,0);
        }    
 </script>
.
.
.
<% for(var i=0; i <todolist.length; i++){ %>
                <lt> <%= todolist[i].name %></lt>
                <button onclick = "rem(i)">x</button><br>
<% } %>

【问题讨论】:

  • 将 todolist.splice(i,0) 更改为 todolist.splice(i,1)。快速查看一下您的 sn-p,您应该就在这之后。

标签: javascript html ejs


【解决方案1】:

Splice 函数的第二个参数定义了要删除的元素数量。在您的代码中,您已通过 0。

todolist.splice(i,0);

请尝试使用类似的东西。

todolist.splice(i,1);

【讨论】:

【解决方案2】:

splice 方法的第一个参数定义数组的索引,第二个参数定义要从数组中删除多少元素。 如果你正在使用

todolist.splice(i, 0);

这意味着你正在删除 0 个元素,所以如果你想删除 1 个元素,那么你必须使用下面的代码

todolist.splice(i, 1);

【讨论】:

  • 抱歉还是不行,可以看看我的作品吗?我已经在github上传了。 github.com/Clifford026/TodoList
  • 您应该在 index.ejs 文件中使用 &lt;button onclick="rem(&lt;%= i %&gt;)"&gt;x&lt;/button&gt; 而不是 &lt;button onclick="rem(i)"&gt;x&lt;/button&gt;。然后您可以访问当前索引。那么你应该在 app.js 中创建一个删除 api 并从 index.ejs 调用。
猜你喜欢
  • 1970-01-01
  • 2021-06-17
  • 2021-03-03
  • 2022-01-23
  • 1970-01-01
  • 2021-12-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多