如何使用多个数据属性和多个逻辑条件选择带有jQuery的li

时间:2012-01-16 12:55:48

标签: javascript jquery jquery-selectors

我有一个产品列表,我想过滤客户端。产品列表是一个多个li的ul,如下所示:

<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如何选择具有例如的li: (数据位置中的值为2或4)AND(数据属性中的值为3或4)AND(数据位置中的值为1或2或3)。

3 个答案:

答案 0 :(得分: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 :(得分:1)

您可以filter li个元素并使用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中值为2或4且data-property中值为4或5的所有data-format元素。您可以根据需要添加任意数量的条件,只需确保使用括号正确分组。

答案 2 :(得分: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);