2012-02-08 32 views
0

通过checkboxex是基于我刚才的问题在这里问: Jquery Filter List DIVs via checkboxes 我在当两个复选框和列表可以从JavaScript,所以如果我在查看源文件看,我便无法看到它们产生的一发。 我设法找到了,我可以访问通过复选框:过滤器列表事业部通过DOM

$(".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(); 
      } 
     }); 
    }); 

谢谢

+0

你可以张贴一些示例HTML? – magicalex 2012-02-08 16:38:55

回答

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); 
+0

非常感谢你似乎正是我需要的只是我真的尝试过,我无法做到这一点工作..你可以请添加这个工作在http:// jsfiddle请再次感谢你 – Teodor 2012-02-08 15:22:11

+0

$(this).data('卧室')似乎没有定义... – Teodor 2012-02-08 15:36:54

+0

@Teodor;你可以检查jsfiddle链接吗? – 2012-02-08 19:55:24