【发布时间】:2025-11-25 23:00:01
【问题描述】:
我有两个复选框。当我选中一个时,代码将获取该复选框的状态和 id 并推送到数组中,如果该值尚不存在
数组集合变成这样
[8,0] [10,0]
要求:
- 如果我检查然后取消选中并再次检查它,它会插入 [8,0] [8,0] 两次,所以这不应该插入多次相同的值
- 从数组集中删除特定数组,因此如果我取消选中 chkecbox,则仅删除 [8,0] 但保留 [10,0]
var positions = [];
$("body").on('click', '.check_box', function() {
var id = $(this).attr('data-id');
var status = $(this).attr('data-status');
if ($(this).prop("checked") == true) { // if click on check
if (!$.inArray(id, positions)) positions.push(id); // if id and status not in array then only push
positions.push([id, status]); // it will insert like [8,10] but geting duplicate [8,10] [8,10]
console.log(positions);
} else {
// if uncheck checkbox
// remove specific value like [8,0] or if value present [10,0] then remove this
console.log(positions);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check_box" data-id="8" data-status="0">
<input type="checkbox" class="check_box" data-id="10" data-status="0">
【问题讨论】:
-
你需要在删除数组中的值时检查索引,你可以使用
splicehttps://www.w3schools.com/jsref/jsref_slice_array.asp -
我给你做了一个sn-p。
-
@jishansiddique 我也试过了,但它没有像 [8,0] 那样删除单个集合
标签: javascript jquery arrays push