2010-11-22 54 views
2

我需要关于在jQuery中进行一些过滤的最佳方法的建议。使用jQuery进行高级过滤,需要最佳方向

HTML

我有一个包含属性的unorderd列表形式:

<form name="attrList"> 

    <ul> 
     <li> 
      <input type="checkbox" name="FILTER" value="1+" /> 1+ 
     </li> 
     <li> 
      <input type="checkbox" name="FILTER" value="Adrian Chesterman" /> Adrian Chesterman 
     </li> 
     <li> 
      <input type="checkbox" name="FILTER" value="Green" /> Green 
     </li> 
    </ul> 

</form> 

然后我有一套的div。我给的div “attrList” 的属性,比如:

<div class="productContainer" attrList="1+,Andy Thomas"> 
    <h3>Some Name Here</h3> 
    <ul> 
     <li>1+</li> 
     <li>Andy Thomas</li> 
    </ul> 
</div> 

jQuery的

  1. 当任何输入[名称= FILTER]点击,我建立的所有名单输入[名称= FILTER]:检查。
  2. 我在循环所有div
  3. 在循环过程中,我检查该div上的attrList属性(例如attrList =“red”)以查看是否在该列表中找到了被单击的内容。
  4. 如果没有找到我移动DIV的视线到不同的div

JSBin例

上面的例子已被简化,所以你可以看到什么样的基础知识我在做。 JSBin Link Here

需要你的意见

这是我第一次去这样做这种过滤;我只是从以前来过的人那里寻找最佳做法。我真的很感激你的反馈!

+0

如果您可以将您的问题限制在100个字或更少,尽可能少的代码仍然可以证明问题,那么您在这里的成功机会将大大增加。 – ken 2010-11-22 16:33:54

+1

您应该考虑使用jQuery的data()方法代替attrList =“...”....链接1:http://api.jquery.com/data/链接2:http://api.jquery .com/jQuery.data/ – ken 2010-11-22 16:37:41

回答

1

这是我的头顶,没有经过测试或优化。但是像这样的东西应该工作。

//Hide divs with tag value 
function hide_stuff(tag_value) 
{ 
    $(".productContainer") 
    .filter('[attrList*="'+tag_value+'"]') 
    .each(function(i){ 
     $(this).hide() 
    } 
); 
} 
//Bind events to form 
$("form[name='attrList'] input[name='FILTER']").live('change', function(evt){ 
    if($(this).is(':checked')){ 
    var tag = $(this).val(); //e.g. 'Andy Thomas' 
    hide_stuff(tag); 
    } 
}); 

如果你打算做甚至中间jQuery的工作,这个页面是一个必须阅读http://api.jquery.com/category/selectors/

编辑:这是你会怎么做。数据$,而不是类似的事情(这仅仅是一个更好在属性中存储数据的方式)。

//Hide divs with tag value 
function hide_stuff(tag_value) 
{ 
    $(".productContainer").filter(function() { 
     return $.inArray(tag_value, $(this).data('tags')); //e.g.'Andy Thomas' is 'tags' data 
    } 
    ) 
    .each(function(i){ 
     $(this).hide() 
    } 
); 
} 
//Bind events to form 
$("form[name='attrList'] input[name='FILTER']").live('change', function(evt){ 
    if($(this).is(':checked')){ 
    var tag = $(this).val(); //e.g. 'Andy Thomas' 
    hide_stuff(tag); 
    } 
}); 
//jQuery 1.4.3+ only - http://api.jquery.com/data/ 
<div class="productContainer" data-tags="[1+, Andy Thomas]"> 
    <h3>Some Name Here</h3> 
    <ul> 
     <li>1+</li> 
     <li>Andy Thomas</li> 
    </ul> 
</div>