Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 选择数据属性中至少有一个值的元素,该属性包含在特定数组中_Javascript_Jquery_Arrays_Sorting - Fatal编程技术网

Javascript 选择数据属性中至少有一个值的元素,该属性包含在特定数组中

Javascript 选择数据属性中至少有一个值的元素,该属性包含在特定数组中,javascript,jquery,arrays,sorting,Javascript,Jquery,Arrays,Sorting,我正在编写一个过滤函数,其中我需要选择在其数据属性中具有特定值的元素,这些值包含在数组中,请允许我在一个示例中解释: 例如,我有三个元素和一个按钮,如下所示: <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="a

我正在编写一个过滤函数,其中我需要选择在其数据属性中具有特定值的元素,这些值包含在数组中,请允许我在一个示例中解释:

例如,我有三个元素和一个按钮,如下所示:

<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>
Select
变量如何针对前两个元素,因为第一个元素同时具有“aa”和“ff”,第二个元素具有“ff”

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

您可以使用:

让我们为此使用:

$(“.button”)。单击(函数(){
//首先,我从按钮的数据属性创建一个数组
var myArray=$(this).data('boo').split(',');
//Select应该是其da foo至少有一个元素的元素
//-上面数组中的值
var Select=$(“div[data foo]”;//选择包含数据foo的所有元素
选择。每个(函数(索引、元素){
变量isInMyArray=$(元素).data(“foo”).split(“,”).some(函数(元素){
if(myArray.indexOf(element)!=-1)
{return true;}//如果为true,则元素位于myArray中
});//此处使用一些-如果在数组中找到一个值,则返回true。
console.log(isInMyArray);
});
});

测试
$( ".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 = "?"

});
$( ".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(','));
});