[英]jQuery if data attribute add class
I'm really new to JS and jQuery, but I try adding a class "hide" to an element if it has a data attribute with a specific string.我对 JS 和 jQuery 真的很陌生,但是我尝试将 class “隐藏”添加到一个元素,如果它有一个带有特定字符串的数据属性。 So if "class" hat a data-rating attribute of "0.0", the class "hide" should be added.因此,如果“类”的数据评级属性为“0.0”,则应添加 class“隐藏”。 It doesn't work and I don't know why.它不起作用,我不知道为什么。
$(document).ready(function() {
if ($(".class").data('rating') === ('0.0')){
$(".class").addClass('hide');
}
});
jQuery recognises data-rating="0.0"
as numeric, so when you call $(".class").data('rating')
you get the number 0
. jQuery 将data-rating="0.0"
识别为数字,因此当您调用$(".class").data('rating')
时,您会得到数字0
。 Hence, strictly comparing it to any string will fail.因此,严格将其与任何字符串进行比较都会失败。
Additionally, your code will not behave as expected if there is more than one element with the given class.此外,如果给定 class 的元素不止一个,您的代码将不会按预期运行。
$(".class").each(elem=>{
const $elem = $(elem);
if( $elem.data('rating') === 0) {
$elem.addClass('hide');
}
});
Or, without jQuery (and therefore immeasurably faster)...或者,没有 jQuery (因此速度快得不可估量)......
document.querySelectorAll(".class").forEach(elem=>{
if( parseFloat(elem.getAttribute("data-rating")) === 0) {
elem.classList.add("hide");
}
});
Rapid shift back to jQuery, you could also do this:快速切换回 jQuery,您也可以这样做:
$(".class[data-rating='0.0']").addClass('hide');
... as a one-liner. ......作为单线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.