jQuery检查data-*属性是否包含带$(this)的值,然后执行某些操作
HTML:jQuery检查data-*属性是否包含带$(this)的值,然后执行某些操作,jquery,match,custom-data-attribute,Jquery,Match,Custom Data Attribute,HTML: <!-- a class with a data-target attribute with a list of space-seperated values --> <div class="class1" data-target="value1 value2 value3 ..."> ... </div> <!-- and there might be more than one objec
<!-- a class with a data-target attribute with a list of space-seperated values -->
<div class="class1" data-target="value1 value2 value3 ...">
...
</div>
<!-- and there might be more than one object with the same class but with same and/or different data-target values -->
<div class="class1" data-target="value4 value5 value2 ...">
...
</div>
// looping through each class1 to see if it contains a value and if so do something
$.each($('.class1'), function(){
if ($(this)...) { // check if data-target of this specific object with class1 contains the value
// do something
}
});
要检查此class1特定对象的数据目标是否包含我想要的类似值,请执行以下操作:
element[data-target~="value5"]
但是美元(这个)
我试过:
if ($(this).attr('[data-target~="value5"]')) ... // doesn't work (don't know why)
if ($('.class1[data-target~="value5"]')) ... // works but apply to all class1 objects and not just the specific one I'm testing
if ($(this).data('target').match('value5')) ... // works but is akin to *= and I want all the match options like ~= |= ^= etc.
但究竟是什么原因。。。我需要能够对$('this')应用与[data target~=“value*”]等价的东西
因此,有两个问题:
一些jquery方法采用
选择器,而其他方法则不采用
.attr()
不使用选择器,因此您不能在.attr()
中使用[data target]
,而只是属性名的一个简单字符串,.attr(“data target”)
——因此这与您的.data(“target”)
示例类似,在该示例中,您可以使用js根据需要检查值
相反,您可以使用.is()
或.filter()
:
$.each($('.class1'),function(){
如果($(this).is(“[data target~='value3']”)为”{
console.log(“是的”);
}
其他的
log(“不,不是”);
});代码>
目标
目标
if ($(this).is('[data-target~="value5"]'))