我正在构建一个 jQuery 过滤器,它通过 2 组标准(水果类型和颜色)过滤列表。例如,如果用户按水果类型“浆果”过滤,则只会显示浆果。然后,如果它们按水果颜色“红色”过滤,则只会显示红色浆果。
我认为问题在于我的fruitColor 和fruitType 变量的设置方式。我试图使这些变量的值等于已单击的锚标记的数据类型。我的代码如下,谢谢!
jQuery:
$(document).ready(function()
{
$("ul.filter li a").click(function()
{
var fruitColor = $('ul#fruitColor li a').attr('data-value');
var fruitType = $('ul#fruitType li a').attr('data-value');
var fruitColorSelector = '';
var fruitTypeSelector = '';
if (fruitColor == "all" && fruitType == "all")
{
//show all items
$(".item").show();
}
else
{
if (fruitType != "all")
{
fruitTypeSelector = '.' + fruitType
}
if (fruitColor != "all")
{
fruitColorSelector = '.' + fruitColor
}
$(".item").hide();
$(fruitTypeSelector + fruitColorSelector).show();
}
});
});
HTML:
Select Color Category:
<ul class="filter" id="fruitColor">
<li><a data-value="all">Any Color</a></li>
<li><a data-value="red">Red</a> </li>
<li><a data-value="blue">Blue</a> </li>
<li><a data-value="yellow">Yellow</a> </li>
</ul>
<br>
Select Fruit Type:
<ul class="filter" id="fruitType">
<li><a data-value="all">Any Type</a> </li>
<li><a data-value="fruit">Fruit</a> </li>
<li><a data-value="berry">Berry</a> </li>
</ul>
<br>
<ul>
<li class="item red fruit">Apple</li>
<li class="item blue fruit">Grape</li>
<li class="item yellow fruit">Lemon</li>
<li class="item red fruit">Cherry</li>
<li class="item yellow fruit">Banana</li>
<li class="item red berry">Strawberry</li>
<li class="item blue berry">Blueberry</li>
<li class="item red berry">Raspberry</li>
<li class="item yellow fruit">Pineapple</li>
<li class="item yellow berry">Yellowberry</li>
</ul>