删除&清除所选属性过滤器

时间:2015-05-12 15:42:10

标签: javascript jquery

在我的产品列表tempalte上,我有一些过滤器ul.current-filters li,显示当前所选的产品属性。点击后,过滤器按钮应该消失ul.current-filters li。点击"清除过滤器"按钮.clear-current-filters,应删除所有过滤器。如果只剩下一个过滤器,则应将其与清除过滤器按钮一起移除。

enter image description here

HTML

<div class="product-filter-buttons-container">
        <!-- Product Filter list -->
        <ul class="current-filters">
        <div class="clear-current-filters">Clear Filters<a href="#">x</a></div>
        <!-- Product Filter Attributes -->
        <li>Nike<a href="#">x</a></li>
        <li>Adidas<a href="#">x</a></li>
        <li>£90 - £100<a href="#">x</a></li>
    </ul>
</div>

JQuery - 这是我目前所拥有的,遗憾的是它无法正常运行。如何引用delgated元素?好像$(this)引用了最初的ul.current-filters li

$(".product-filter-buttons-container").on("click", "ul.current-filters li", function(event) {
       event.preventDefault();
        var a = $(this);

        if ((a.length) > 0) {
            a.hide();
        } else {
            a.hide();
            $(".clear-current-filters").hide();
        }
});

1 个答案:

答案 0 :(得分:2)

这样的事情:

$('.current-filters > li > a').click(function(e){
   var $this = $(this),
       clearAll = $this.parent('li').hasClass('clear-current-filters'),
       lastOne = $('.current-filters > li ').length == 2;

    if(clearAll || lastOne){
        $this.closest('ul').empty();
    }else{
        $this.parent().remove();
    }
});

为此:

<div class="product-filter-buttons-container">
    <!-- Product Filter list -->
    <ul class="current-filters">
        <li class="clear-current-filters">
            Clear Filters<a href="#">x</a>
        </li>
        <li>
            Nike<a href="#">x</a>
        </li>
        <li>
            Adidas<a href="#">x</a>
        </li>
        <li>
            £90 - £100<a href="#">x</a>
        </li>
    </ul>
</div>

查看工作in this demo