通过DOM过滤列表Div的via checkboxex

时间:2012-02-08 00:27:32

标签: jquery dom

根据我之前提出的问题: Jquery Filter List DIVs via checkboxes 我遇到了这样的情况,当复选框和列表都是从javascript生成的,所以如果我查看源代码我看不到它们。 我设法发现我可以通过以下方式访问复选框:

$(".bedroomType").attr("type", "input").change(function(){}

但我不能使列表过滤... 在这种情况下应该如何更改此代码?

 $(".bedroomType").attr("type", "input").change(function(){
   $(".bedroomType").attr("type", "input").each(function(){

        var checked = $(this).attr('checked') || false;
        var numberofrooms = $(this).data('bedrooms');
        alert(numberofrooms);
        $('.listing').each(function(){
            if ($(this).data('bedrooms')==numberofrooms){
                checked ? $(this).show() : $(this).hide();
            }
        });
    });

谢谢

1 个答案:

答案 0 :(得分:0)

您的示例代码无法使用,因为您无法为列表中的show()hide()项授予过滤权限。一般情况下,过滤器应为show()hide()(或类似),在这种情况下应为hide()

您会发现将代码组织到调用“卧室”过滤器和(最终)其他过滤器的“主”过滤器更方便。主人应确保最初显示所有列表项,以便过滤器可以选择性地隐藏它们。

很有可能认为你可以选择反过来做事 - 即最初hide()所有项目,然后允许过滤器有选择地show()。但这不起作用,因为没有单独的过滤器应该具有show()的权限 - 其他过滤器可能有不同的意见!使用此类型的过滤器集,您希望项目仅在符合所有条件时显示,而不是任何条件。

以下是一些代码:

function filterListingByBedrooms($listing){
    var selectedBeds = [];
    $(".bedroomType").each(function(){
        if(this.checked) {
            selectedBeds.push($(this).data('bedrooms'));//build array of checked bedroom numbers
        }
    });
    $listing.each(function(){
        var $this = $(this);
        if(!$.inArray($this.data('bedrooms'), selectedBeds)) {
            $this.hide();
        }
    });
}

function filterListingByType($listing){
    ...;
}

function filterListingByLocation($listing){
    ...;
}

function filterListing(){
    var $listing = $('.listing').show();//Initially show all, then allow filters to selectively hide.
    filterListingByBedrooms($listing);
    filterListingByType($listing);//apply other filter
    filterListingByLocation($listing);//apply other filter
};

$(".bedroomType").change(filterListing);
$(".propertyType").change(filterListing);
$(".location").change(filterListing);
相关问题