一开始使用的是includes函数,只能进行简单的模糊 搜索,并不能执行多条件以及精准搜索,较为简陋,后续更改为filter来进行多条件搜索
const filters = {
name_search: $("#search").val(),
title_search: $(".search").val(),
id_company: $(".companys").val(),
tradeid_industry: $(".Selection_box .Industry").val(),
title_goods: $(".Details_text").val(),
name_person: $("#office_Person").val(),
company_office: $("#office_name").val(),
title_simple: $("#office_simple").val(),
cattitle_sort: $(".search_content .office_sort").val(),
};
// 过滤空值字段
Object.keys(filters).forEach((key) => {
if (!filters[key] || filters[key] == 0) delete filters[key];
});
通过将所有数值放入条件内,因为后续使用的是通过键值名来与数据内对应的数据进行比对,有多个后台接口进行对应,所以数据名称会重复,若在这里进行相同名字的声明则会使数据相互覆盖,造成错误,因此使用这样的命名方式来区分
const newArr = performFilter(data, filters);
// 处理筛选结果
if (newArr.length === 0) {
$(".Notice")
.html('<img src="img/none.png" alt="" class="none_pic">')
.css("display", "flex");
$(".Notice_nav, .Notice_footer").hide();
} else {
render(newArr);
$(".Notice_nav, .Notice_footer").show();
$(".Notice").show();
data = newArr;
render(data);
}
随后调用函数,并处理无数据的结果
function performFilter(items, filters) {
return items.filter((item) => {
return Object.entries(filters).every(([key, filterValue]) => {
// 不再通过 key.split('_') 来拆解字段名
const fieldName = key.split("_")[0];
// 如果 filterValue 为空,跳过筛选
if (!filterValue) return true;
// 处理筛选
if (item[fieldName] === undefined) {
// 如果字段不存在于 item 中,跳过这个条件
return true;
}
// 对于字符串的匹配,使用 includes 进行模糊匹配
if (typeof item[fieldName] === "string") {
// 使用 includes 来判断是否包含输入的部分内容
return item[fieldName]
.toLowerCase()
.includes(filterValue.toLowerCase());
}
// 对于其他类型的字段,进行直接比较
return item[fieldName] == filterValue;
});
});
}
首先循环遍历对象的每一个键值对,并返回出来结果,因为我前面说的,为了防止相互覆盖,但又需要其名字来作为检索的依据,因此用下划线分割,同时将前面我需要的部分截取下来并赋值给一个变量,判断一下空点搜索的可能性,随后进行判断,当为字符串的时候进行模糊搜索,为数字的时候进行精确比对,将值返回给上级,再通过循环遍历的每一个键值对中为true的生成一个新数组返回到最外面赋值给newArr,进行渲染。