我正在编写一个过滤函数,我需要在其数据属性中选择具有特定值的元素,并且这些值包含在数组中,允许我在一个示例中解释它:
例如,我有三个元素和一个按钮,如下所示:
<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>
每个元素中的data-foo包含以逗号分隔的值。当我点击按钮时,我从其数据属性创建一个数组( myArray
在下面的代码中),然后我需要选择那些至少有一个值的元素myArray
在他们的数据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”。
我真的试着把它说得有道理,如果不够清楚,请告诉我,我会很乐意解释更多,谢谢。
答案 0 :(得分:2)
您可以使用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(','));
});
答案 1 :(得分:0)
让我们使用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);
});
});
&#13;
<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>
&#13;