2012-01-16 10 views
0

我有一個產品列表,我想過濾clientside。的產品列表是具有多個立的像這樣的一個UL:如何使用jQuery選擇使用多個數據屬性和多個邏輯條件的li

<li data-property="2,3,4" data-format="1,2,3,4,5" data-location="1,2,4" data-id="9"> 
         Product A is fantastic 
</li> 

使用jQuery如何可以選擇立的具有例如: (值2或4中數據位置)AND(值3或4數據屬性)AND(數據位置中的值1或2或3)。

+0

如果這將使解決方案更容易,數據屬性可以使用空格分隔符而不是逗號分隔符 – murze 2012-01-16 13:04:43

回答

2

你可以創建一個自定義表達式:

$.expr[':'].myProductFiltered = function(obj){ 
    var $obj = $(obj), 
     d_p = $obj.data('property').split(','), 
     d_f = $obj.data('format').split(','), 
     d_l = $obj.data('location').split(','); 

    return ($.inArray("3", d_p) > -1 || $.inArray("4", d_p) > -1) /* values admitted in data-property */ 
     && ($.inArray("2", d_l) > -1 || $.inArray("4", d_l) > -1) /* values admitted in data-location */ 
     && ($.inArray("3", d_f) > -1 || $.inArray("4", d_f) > -1) /* values admitted in data-format */ 
     /* add as many filters you need */ 
}; 

,並選擇與

$('li:myProductFiltered') 

看到現場小提琴:http://jsfiddle.net/VgTnG/

1

您可以filterli元素和使用split來創建各種data-*屬性的值的數組。然後,可以使用indexOf來測試各種值在這些陣列中的存在:

$("li").filter(function() { 
    var li = $(this), 
     property = li.data("property").split(","), 
     format = li.data("format").split(","), 
     location = li.data("location").split(","); 
    return (property.indexOf("2") > -1 || property.indexOf("4") > -1) && (format.indexOf("4") > -1 || format.indexOf("5") > -1); 
}); 

以上例子將返回所有li元件與data-format的2或4 data-property的值和值4或5 。您可以根據需要添加儘可能多的條件,只要確保使用圓括號將它們正確分組即可。

1

難道你試試這個http://jsfiddle.net/sabri/gmt8m/

var conditions = { 
    'data-format': ['4', '1'], 
    'data-location': ['5', '2'] 

} 

var result = $('li').filter(function(index) { 
    var current_li = $(this); 
    var and_cond = true; 
    $.each(conditions, function(key, value) { 
     var or_cond = false; 
     $.each(value, function(skey, svalue) { 
      or_cond = or_cond || (jQuery.inArray(svalue, current_li.attr(key).split(',')) != -1) 
     }) 
      and_cond = and_cond && or_cond; 
    }) 
    if(and_cond) 
     return current_li ; 


}) 

console.log(result); 
+0

,這不起作用。當使用

  • 產品A太棒了
  • 產品B是奇妙
  • 作爲輸入產品B我用這個條件陣列 變種條件= { 「數據格式」返回以及 – murze 2012-01-17 13:42:03

    +0

    :「4」,「1」], 「數據位置」:[ '5','2'] } 且只有A被選中 檢查控制檯。 檢查這個小提琴http://jsfiddle.net/sabri/b6WKn/ – 2012-01-19 09:11:52

    相關問題