选择数据属性中至少包含一个值的元素,它包含在某个数组中

问题描述:

我正在编写一个过滤函数,我需要选择其数据属性中具有特定值的元素,而那些元素值包括在一个阵列,允许我解释它在一个例子:选择数据属性中至少包含一个值的元素,它包含在某个数组中

例如,我有三个元件和一个按钮如下:

<div data-foo="aa,cc,ff" ></div> 
<div data-foo="bb,cc,ff" ></div> 
<div data-foo="bb,dd,ee" ></div> 

<div class="button" data-boo="aa,ff" ></div> 

数据-FOO中的每个元素都包含逗号分隔值。当我点击按钮时,我从它的数据属性中创建了一个数组(myArray,代码),然后我需要选择那些至少其中一个值为myArray的元素在他们的data-foo中,一个明确的解释,请参见下面的代码:

$(".button").click(function() { 

    // First I make an array from the button's data attribute 
    var myArray = $(this).data('boo').split(','); 


    // Select should be elements that their da-foo has at least one 
    // — of values in the array above 
    var Select = "?" 

}); 

如何Select变量可以针对前两个元素,由于第一个具有两个“AA”和“FF”,并且所述第二元件具有“FF”。

我真的试过把它说得有道理,如果不够清楚,请让我知道,我会很乐意解释更多,谢谢。

您可以使用Attribute Contains Selector

$(".button").click(function() { 
    // First I make an array from the button's data attribute 
    var myArray = $(this).data('boo').split(','); 

    // produces array of strings like '[data-foo*="aa"]' 
    var selectors = myArray.map(function(value) { 
     return '[data-foo*="' + value + '"]'; 
    }); 
    // searches by selectors joined by comma, returns all elements 
    // that satisfy at least one selector 
    var selectedElements = $(selectors.join(',')); 
}); 
+0

谢谢你,米卡莱。它工作完美。 – Ogdila

允许使用Array.prototype.some此:

$(".button").click(function() { 
 

 
    // First I make an array from the button's data attribute 
 
    var myArray = $(this).data('boo').split(','); 
 

 

 
    // Select should be elements that their da-foo has at least one 
 
    // — of values in the array above 
 
    var Select = $("div[data-foo]"); //select all elements with data-foo 
 
    Select.each(function(index, element) { 
 
    var isInMyArray = $(element).data("foo").split(",").some(function(element) { 
 

 
    if (myArray.indexOf(element) != -1) 
 
     {return true;}//if true then element is in myArray 
 

 
    }); //using some here - if one value is found in array return true. 
 
    console.log(isInMyArray); 
 
    }); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div data-foo="aa,cc,ff"></div> 
 
<div data-foo="bb,cc,ff"></div> 
 
<div data-foo="bb,dd,ee"></div> 
 

 
<div class="button" data-boo="aa,ff">test</div>