我有以下代码(也在 JSFIDDLE 上启动并运行:http: //jsfiddle.net/DSuua/12/)
它根据价格匹配对产品进行分类。如果在该价格范围内没有产品,我想在页面加载时完全隐藏左侧面板列表中的过滤器选项(与显示价格范围相比,无论如何,就像我现在所做的那样)。
因此,例如,如果在 10 - 20 的价格范围内没有产品,则隐藏左侧面板上的“$10 - $20”,因为它无关紧要,它只会向用户显示令人讨厌的“未找到匹配”消息。
现在过滤是在点击事件上执行的。在过滤完成之前,它需要首先检查列表属性值(名称、标题)和产品价格值(最低和最高价格),如果没有找到匹配范围,则从列表中隐藏这些过滤项。
我仅限于客户端的此解决方案。
此外,欢迎任何改进此代码的整体提示。
HTML:
<ul id="filterByPrice">    
    <li><span class="section-header">PRICE</span></li>    
    <li><a href="#" title="">Any Price</a></li>
    <li><a href="#" name="0" title="9">Under $10</a></li>
    <li><a href="#" name="10" title="19">$10 - $20</a></li>
    <li><a href="#" name="20" title="29">$20 - $30</a></li>
    <li><a href="#" name="30" title="39">$30 - $40</a></li>
    <li><a href="#" name="40" title="49">$40 - $50</a></li>
    <li><a href="#" name="50" title="9999">Over $50</a></li>
</ul>
<ul id="products">
    <li>
        <a href="/product-one">Product One</a><br>
        <span id="lowestPriceRange">0</span>
        <span id="highestPriceRange">9</span>
    </li>
    <li>
        <a href="/product-two">Product Two</a><br>
        <span id="lowestPriceRange">20</span>
        <span id="highestPriceRange">29</span>
    </li>
    <li>
        <a href="/product-three">Product Three</a><br>
        <span id="lowestPriceRange">30</span>
        <span id="highestPriceRange">39</span>
    </li>
    <div id="nothingFound" style="display:none;">
        Nothing found
    </div>
</ul>
CSS:
#filterByPrice, #products {
 border:1px solid #ccc;
 padding:10px;  
 width:100px; 
 margin:10px; 
 float:left;
 position:relative;   
}
JS:
var noProductMatches = $('#nothingFound');
$('#filterByPrice li a').click(function() 
{
    noProductMatches.hide();
    var priceRangeSelectedItem = $(this).html().toLowerCase();
    var minSelectedPrice = parseInt( $(this).attr("name") );
    var maxSelectedPrice = parseInt( $(this).attr("title") );
    var productContainer = $('#products li');
    if (priceRangeSelectedItem == 'any price')
    {
        productContainer.fadeOut("slow");
        productContainer.delay(100).fadeIn("slow");
    }
    else
    {
        var results = productContainer
            .fadeOut(100)
            .delay(100)
            .filter(function() 
            {
                var minProductPrice = parseInt( $(this).find("#lowestPriceRange").html().toLowerCase() );
                var maxProductPrice = parseInt( $(this).find("#highestPriceRange").html().toLowerCase() );
                return (minProductPrice >= minSelectedPrice &&  maxProductPrice <= maxSelectedPrice);
            })
            .each(function(index, item) 
            {
                $(item).fadeIn("slow");
            });
            if (results.length == 0)
            {
                noProductMatches.fadeIn();
            }
    }
});
</p>