gpt4 book ai didi

javascript - Splice 删除多个索引

转载 作者:行者123 更新时间:2023-11-28 13:05:49 24 4
gpt4 key购买 nike

我正在制作自己的过滤系统来过滤数据,并且现在正在构建基本功能,例如添加和删除过滤器。

添加过滤器效果很好,但当我尝试添加和删除时,有时 splice 会删除多个过滤器。它为什么要这么做?这是我的代码:

    var active_filters = [];

var available_filters = [
'first_name', 'last_name', 'city'
];

var filters = {
first_name: {
title: 'First Name',
is_active: false,
types: [
{
input: 'text'
},

{
input: 'select',
options: [
'asc', 'desc'
],
values: [
'Ascending', 'Descending'
]
}
],

},

last_name: {
title: 'Last Name',
is_active: false,
types: [
{
input: 'text'
},

{
input: 'select',
options: [
'asc', 'desc'
],
values: [
'Ascending', 'Descending'
]
}
],

},

city: {
title: 'City',
is_active: false,
types: [
{
input: 'text'
},
],

},
};

var id_filters = $("#filters");

$(document).ready(function () {
id_filters.html(template_filters(filters));
});

function template_filters(filters) {
var html = '<select class="select_filters" id="select_filters" onchange="add_filter();">';

html += '<option value="0">Select Filter</option>';

for (var property in filters)
{
if (filters.hasOwnProperty(property))
{
var title = filters[property].title;
var is_active = filters[property].is_active;
var types = filters[property].types;

html += '<option value="'+property+'">'+title+'</option>';
}
}

html += '</select>';

return html;
}

function template_show_filter(filter, filter_name)
{
var html = '<div id="filter-'+filter_name+'" class="div_filter">';

html += '<span>'+filter.title+' <a href="javascript:void(0)" onclick="remove_filter(\''+filter_name+'\')">X</a></span>';

html += '</div>';
return html;
}

function add_filter()
{
var select_filters = $("#select_filters");
var selected_filter = select_filters.val();

if (selected_filter != 0)
{
if (active_filters.length == 0)
{
active_filters.push(selected_filter);
id_filters.append(template_show_filter(filters[selected_filter], selected_filter));
}
else
{
if (active_filters.indexOf(selected_filter) === -1)
{
active_filters.push(selected_filter);
id_filters.append(template_show_filter(filters[selected_filter], selected_filter));
}
}


}
}

function remove_filter(filter_name)
{
var index = active_filters.indexOf(filter_name);



if (index >= 0)
{
var id = $("#filter-"+filter_name);
id.remove();

active_filters.splice(index); // here, it removes more than one
}
}

最佳答案

请查看MDN web docs – Array.prototype.splice() .

如果您只想删除一项,则应调用.splice(index, 1)

如果不指定第二个参数,“那么从起始索引开始到数组末尾的所有元素都将被删除。”

关于javascript - Splice 删除多个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46594645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com