简体   繁体   English

检查数据属性(数组)是否包含值

[英]check if data attribute (array) contains value

is it possible to check if a data attribute (array) contains a specific value?是否可以检查数据属性(数组)是否包含特定值?

element looks like this:元素看起来像这样:

<span id="el" data-id="[1, 2, 10, 3]"></span>
<span id="el" data-id="[4, 3]"></span>
<span id="el" data-id="[6]"></span>

I tried but (obviously) it didn't work:我试过了,但(显然)它没有用:

$('#abcdef').find('[data-id*="3"]');

One of the problems in your example is that multiple elements have the same id Unfortunately, this is not possible with HTML and I suggest you make them classes first.您的示例中的一个问题是多个元素具有相同的id不幸的是,这对于 HTML 是不可能的,我建议您先将它们设为classes

As for your question, it's possible but you would have to do it like so:至于你的问题,这是可能的,但你必须这样做:

 $(function () { $(".element").each(function () { const arr = $(this).data('array'); let text = 'Does not include 2'; if (arr.includes(2)) { text = 'Does include 2'; } $(this).text(text); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="element" data-array="[1,2,3,4]"></div> <div class="element" data-array="[5,6,7]"></div> <div class="element" data-array="[2,3]"></div>

If you don't want to find by class, you can also search by the data attribute, and then use the same code from above to check for presence of a value in the array:如果您不想按 class 查找,您也可以按数据属性搜索,然后使用上面的相同代码检查数组中是否存在值:

$("[data-array]").each(...)

As you're trying to use the 3 as part of the selector to retrieve elements, you can use filter() , like this:当您尝试使用3作为选择器的一部分来检索元素时,您可以使用filter() ,如下所示:

 let id = 3; $('.el').filter((i, el) => $(el).data('id').includes(id)).addClass('foo');
 span { display: block; margin: 3px; }.foo { background-color: #C00; color: #EEE; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span class="el" data-id="[1, 2, 10, 3]">1, 2, 10, 3</span> <span class="el" data-id="[4, 3]">4, 3</span> <span class="el" data-id="[6]">6</span>

Note that I removed the repeated id="el" as it's invalid and changed it to a class .请注意,我删除了重复的id="el"因为它无效并将其更改为class

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

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