我需要一些帮助,我花了一天但仍然无法做到......
<div data-src-object="1" data-src-color="blue" data-src-color="green">Product1</div>
<div data-src-object="2" data-src-color="blue" data-src-color="red">Product2</div>
<div data-src-object="3" data-src-color="green">Product3</div>
<div id="filter">
<span class="label label-info" value="blue">Blue</span>
<span class="label label-default" value="red">Red</span>
<span class="label label-default" value="green">Green</span>
</div>
$('div[data-src-object]').filter(function(){
return ( )
}).hide();
&#34;只显示一个对象,其data-src-color作为.label-info中的值存在,其余的隐藏&#34;
在此示例中,只有product1和product 2可见
我最接近的是:
$(this).attr(&#39; data-src-color&#39;)!= $(&#39; #filter .label-info&#39;)。val()
警报($(本).attr(&#39;数据-SRC色&#39;))
但是警告我发现只显示每个物体的第一种颜色
答案 0 :(得分:0)
您拥有的一个选项是将data-src-color
放在以逗号分隔的值上。
//Get all values of elements with class label-info
let val = $(".label-info").map(function() {return $(this).attr('value')}).get();
//Select all data-src-object and show all
//Filter the data
//Hide data-src-object with no color on val variable
$('div[data-src-object]').show().filter(function() {
let data = $(this).data('src-color').split(',') //Get the src-color data and split to form an array
return !$(data).filter(val).length; //If 2 arrays dont have a common value, return as true
}).hide();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-src-object="1" data-src-color="blue,green">Product1</div>
<div data-src-object="2" data-src-color="blue,red">Product2</div>
<div data-src-object="3" data-src-color="green">Product3</div>
<div id="filter">
<span class="label label-info" value="blue">Blue</span>
<span class="label label-default" value="red">Red</span>
<span class="label label-default" value="green">Green</span>
</div>
&#13;
答案 1 :(得分:0)
请参阅此jsFiddle
HTML
<select id="filter">
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="green">Green</option>
</select>
<div class="color-div" data-src-object="1" data-src-color="blue green">Product1</div>
<div class="color-div" data-src-object="2" data-src-color="blue" data-src-color="red">Product2</div>
<div class="color-div" data-src-object="3" data-src-color="green">Product3</div>
JS
$(document).ready(function(){
$("#filter").on('change', function(){
var selectedColor = $(this).val();
$("div.color-div").each(function(index){
if($(this).attr("data-src-color").indexOf(selectedColor) > -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
$("#filter").change();
});