我有几个复选框,这些复选框根据选择的复选框来过滤产品。单击复选框并将产品ID添加到阵列时,过滤器将起作用。如您所见,两个过滤器都有一些相同的ID,因此,如果它们单击多个输入框,我想确保ID仅被压入阵列一次。例如。如果他们选择了input.white和input.greymelange,那么他们单击了filter-btn我只希望将重复的ID推送一次。有办法吗?
JQUERY
var productIds = [""];
$(document).on('click', 'a.filter-btn', function(e){
$( ".listingTemplate" ).html("");
if ($('input.white').is(':checked')) {
productIds.push("4021401143741", "4021402266227");
}
if ($('input.greymelange').is(':checked')) {
productIds.push("4021401143741", "4021402266227","4021402266418", "4021401143796");
}
});
的HTML
<input type="checkbox" id="white" class="white" value="white" />
<input type="checkbox" id="greymelange" class="greymelange" value="greymelange" />
<a href="#" class="filter-btn">filter</a>
您可以利用$.inArray()
和$.each()
1)将所有新值保留在array中deArray
。
2)使用迭代该数组$.each
,然后查找是否在productIds
使用inArray()
if ($('input.greymelange').is(':checked')) {
var deArray = ["4021401143741", "4021402266227", "4021402266418", "4021401143796"];
$.each(deArray, function (i, j) {
if ($.inArray(j, productIds) == -1) {
productIds.push(j);
}
});
}
建议:不要在数组中声明空字符串。
var productIds = [""]; //considered as an string. This will affect
//when you check length, now it is 1
var productIds = []; //length is 0
最后,
var productIds = [];
$(document).on('click', 'a.filter-btn', function (e) {
$(".listingTemplate").html("");
if ($('input.white').is(':checked')) {
var dArray = ["4021401143741", "4021402266227"];
$.each(dArray, function (i, j) {
if ($.inArray(j, productIds) == -1) {
console.log(j)
productIds.push(j);
}
})
}
if ($('input.greymelange').is(':checked')) {
var deArray = ["4021401143741", "4021402266227", "4021402266418", "4021401143796"];
$.each(deArray, function (i, j) {
if ($.inArray(j, productIds) == -1) {
productIds.push(j);
}
})
}
console.log(productIds)
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句