简体   繁体   English

在jQuery选择器中混合逻辑AND和OR

[英]Mixing logical AND and OR in jQuery selector

I have to filter a list of items, that contain two crucial data attributes: 我必须过滤包含两个关键数据属性的项目列表:

<li class="song" data-title="freedom" data-id="7" data-tags="tag-18-eot,tag-2-eot" data-category="1">Freedom</li>
  1. Category 类别
  2. Tags 标签

Filtering by category should be by logical OR but filtering by tags should be by logical AND. 按类别过滤应按逻辑或,但按标签过滤应按逻辑与。

Filtering using one of these two is not a problem. 使用这两者之一进行过滤不是问题。

I applied, for example: 我申请了例如:

$(collection).filter('li[data-tags*="tag-50-eot"][data-tags*="tag-51-eot"]');

to filter by tags. 按标签过滤。 Or: 要么:

$(collection).filter('[data-category="1"], [data-category="2"]);

to filter by category. 按类别过滤。

This works fine. 这很好。 However, i could not find a way to combine these two selectors into one single query that i can pass to the filter() function, and chaining two filter() calls does not lead to the desired result, because the first call might filter out items that the second call would leave behind. 但是,我找不到将这两个选择器组合成一个可以传递给filter()函数的单个查询的方法,并且链接两个filter()调用不会产生所需的结果,因为第一个调用可能会过滤掉第二个呼叫将留下的项目。

I found this question with a similar topic, but the problem is a little different and the approach as well. 我发现这个问题的主题相似,但是问题和方法也有所不同。

How can I filter those items correctly? 如何正确过滤这些项目?

You should be able to get what you are looking for with chaining, as long as you use the AND condition first. 只要先使用AND条件,就应该可以通过链接获得所需的内容。 For example: 例如:

var res = $('#collection li')
    .filter('li[data-tags*="tag-50-eot"][data-tags*="tag-51-eot"]')
    .filter('[data-category="1"], [data-category="2"]'); 

Fiddle here . 在这里摆弄。

the filter function can receive a function as input... 过滤器函数可以接收一个函数作为输入...

You may end up with a construct like: 您可能会得到类似以下的构造:

var set = $(collection).filter(
function( index, element )
{
    return ($(element).attr(...) == "...");
}
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM