Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在单击按钮时从数组中删除项目_Javascript_Jquery_Arrays - Fatal编程技术网

Javascript 如何在单击按钮时从数组中删除项目

Javascript 如何在单击按钮时从数组中删除项目,javascript,jquery,arrays,Javascript,Jquery,Arrays,我有一个只有几行的表格和删除按钮。我已将所有表列表存储在数组“arr”中。如何在单击按钮时从该数组中删除选定项 <table id="sum_table"> <tr class="titlerow"> <th>S.N.</th> <th>Name</th> <th>Action</th> </tr> <tr> <td>1&l

我有一个只有几行的表格和删除按钮。我已将所有表列表存储在数组“arr”中。如何在单击按钮时从该数组中删除选定项

<table id="sum_table">
  <tr class="titlerow">   
    <th>S.N.</th>
    <th>Name</th>
    <th>Action</th>
</tr>
<tr>
    <td>1</td>
    <td>John</td>
    <td><button class="dm" data-id="0">Remove</button></td>
</tr>
<tr>
    <td>2</td>
    <td>Henry</td>
    <td><button class="dm" data-id="1">Remove</button></td>
</tr>
</table>

 var arr= [
  ["name", John],
  ["name", Henry]
  ];

  function clickHandler(clickEvent) {

}

document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('click', clickHandler);
});

S.N。
名称
行动
1.
约翰
去除
2.
亨利
去除
var arr=[
[“姓名”,约翰],
[“姓名”,亨利]
];
函数clickHandler(clickEvent){
}
document.addEventListener('DOMContentLoaded',function(){
document.addEventListener('click',clickHandler);
});

假设您在单击事件时发送此人的姓名,然后您可以使用
数组。拼接方法,如下所示:

for(var i = arr.length - 1; i >= 0; i--) {
    if(arr[i] === name) {
       arr.splice(i, 1);
    }
}
您必须注意,它将从具有相同名称的数组中删除所有值

使用索引-只需单击按钮发送数据id,并在该索引上拼接阵列

arr.splice(dataid, 1)

您的数组需要是对象数组,而不是数组数组。您还可以为表的name列指定一个类来访问其值,然后使用
findIndex
查找数组中name属性的索引,然后使用
splice
将其删除

$(函数(){
var arr=[
{“姓名”:“约翰”},
{“姓名”:“亨利”}
];
$('.dm')。单击(函数(){
var val=$(this.closest('tr').find(“.name”).text();
控制台日志(val);
var index=arr.findIndex(函数(项){return item.name==val})
console.log(索引)
阵列拼接(索引,1)
控制台日志(arr);
})
})

S.N。
名称
行动
1.
约翰
去除
2.
亨利
去除

array.splice
method查看
array.splice
method查找项目的索引,并按照@JohanP的指示使用
arr.splice(index,1)
为什么要更改原始项目的内容array@brk这与更改原始数组的内容无关,只需让他知道使用此方法将删除具有相同名称的数组的所有内容