所以我有了这些基本上是结果的div,我正试图使用复选框和数据类别标记过滤这些结果。
下面是我正在使用的代码,它可以工作,除了它应该只显示DIV,如果它的数据类别标记匹配所有选中的复选框。但在这个脚本中,如果您选择boditrak、trackman和indoor,它将显示每个结果,而不仅仅是包含每个标记的结果。
JSFiddle
<html>
<head>
<title>Test</title>
</head>
<body>
<input type='checkbox' name="sq-filter" value="trackman" id="trackman">trackman<br>
<input type='checkbox' name="sq-filter" value="boditrak" id="boditrak"> boditrak<br>
<input type="checkbox" name="sq-filter" value="kvest" id="kvest">kvest<br>
<input type="checkbox" name="sq-filter" value="slowmotion" id="slowmotion">slowmotion<br>
<input type="checkbox" name="sq-filter" value="indoor" id="indoor">indoor<br>
<p>
<div class="filters">
<div data-id="golfer" data-category="boditrak trackman slowmotion">
<p>Golfer Name - boditrak trackman slowmotion</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion trackman">
<p>Golfer Name - indoor slowmotion trackman</p>
</div>
<div data-id="golfer" data-category="kvest boditrak trackman">
<p>Golfer Name - kvest boditrak trackman</p>
</div>
<div data-id="golfer" data-category="indoor slowmotion">
<p>Golfer Name - indoor slowmotion</p>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var byProperty = [];
$("input[name=sq-filter]").on( "change", function() {
if (this.checked) byProperty.push("[data-category~='" + $(this).attr("value") + "']");
else removeA(byProperty, "[data-category~='" + $(this).attr("value") + "']");
});
$("input").on( "change", function() {
var str = "Include items \n";
var selector = '', cselector = '', nselector = '';
var $lis = $('.filters > div'),
$checked = $('input:checked');
if ($checked.length) {
if (byProperty.length) {
if (str == "Include items \n") {
str += " " + "with (" + byProperty.join(',') + ")\n";
$($('input[name=sq-filter]:checked')).each(function(index, byProperty){
if(selector === '') {
selector += "[data-category~='" + byProperty.id + "']";
} else {
selector += ",[data-category~='" + byProperty.id + "']";
}
});
} else {
str += " AND " + "with (" + byProperty.join(' OR ') + ")\n";
$($('input[name=fl-size]:checked')).each(function(index, byProperty){
selector += "[data-category~='" + byProperty.id + "']";
});
}
}
$lis.hide();
console.log(selector);
console.log(cselector);
console.log(nselector);
if (cselector === '' && nselector === '') {
$('.filters > div').filter(selector).show();
} else if (cselector === '') {
$('.filters > div').filter(selector).filter(nselector).show();
} else if (nselector === '') {
$('.filters > div').filter(selector).filter(cselector).show();
} else {
$('.filters > div').filter(selector).filter(cselector).filter(nselector).show();
}
} else {
$lis.show();
}
$("#result").html(str);
});
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
</script>
</html>