如何解决获取所选 LI 的值并将其从数组中删除
我有一个用户输入的字符串列表,希望能够删除一个单独的项目,同时也将它从数组中删除。我可以从 DOM 中成功删除它,但不能从数组中删除。
到目前为止,我已经尝试获取所选 LI 的值并选择该特定 LI 的索引
$(document).on('click','button.delete',function () {
let deletedItem = $(this).closest('li')
let itemValue = $(this).closest('li').val()
let index = items.indexOf(itemValue);
if(index != -1) {
items.splice(index,1);
}
deletedItem.remove();
});
这不会从我的数组中删除它,任何想法如何完成?
解决方法
// To delete element from an array you had to keep track of the index in which the element exist. check the below example:
// Create an array of strings;
let array = ["Hello","Boy","Happy","Fun"];
// search for the index of item to be deleted in array
let index = array.indexOf("Boy");
console.log(index); // output: 1;
// The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements
array.splice(index,1); // Return the removed item;
// Check item present
console.log(array); // output: [ 'Hello','Happy','Fun' ];
试试这个
let items = [1,2];
$(document).on('click','button.delete',function () {
let deletedItem = $(this).closest('li')
let itemValue = $(this).closest('li').val()
let index = items.indexOf(itemValue);
if(index != -1) {
items.splice( index,1); // <-- Do this
}
deletedItem.remove();
console.log(items);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>
<li value="1">
<button class="delete">Delete</button>
</li>
<li value="2">
<button class="delete">Delete</button>
</li>
<li value="3">
<button class="delete">Delete</button>
</li>
<li value="4">
<button class="delete">Delete</button>
</li>
</ol>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。