如果jQuery的数据属性为true



我的代码有问题。如果data属性为true,我将尝试为div添加背景色。这是我的HTML代码:

<html data-highcontrast-applied="true">
<head>
</head>
<body>
<div class="row-centered">
<p>
Helllllllooooooooooo
</p>
</div>
</body>
</html>

这是jQuery代码

$(document ).ready(function() {
if(typeof $("html").attr('highcontrast-applied')  == 'true')
{
$(".row-centered").css({"background-color": "red"});
}
});

有人能帮我吗?这也是一个jsfiddle链接:https://jsfiddle.net/dmv9o3ep/2/

尝试删除typeof并获取该属性(如字符串(的值,然后将其与"true"进行比较

$(document ).ready(function() {
if($("html").attr('data-highcontrast-applied').toString() == 'true')
{
$(".row-centered").css({"background-color": "red"});
}
});

代码的问题是:

  1. 您没有正确获取html属性的值;

  2. $("html").attr('data-highcontrast-applied')上的typeof将返回boolean,而不是html属性的值;

我会将data-*属性设置为10,然后使用parseInt并检查它是否等于1,然后应用背景(或您想要的任何其他css属性(:

$(document).ready(function() {
if (parseInt($("html").attr('data-highcontrast-applied')) === 1) {
$(".row-centered").css({
"background-color": "red"
});
}
});

https://jsfiddle.net/eht9faoz/

您可以阅读更多关于jQuery.data().attr()的信息:https://stackoverflow.com/a/7262427/867418

您拼错了属性名称,请尝试以下操作:

$(document).ready(function() {
if(typeof $("html").attr("data-highcontrast-applied"))
{
$(".row-centered").css({"background-color": "red"});
}   
});

您不需要在中使用typeof

$(function() {
if($("html").data('highcontrast-applied') == true) {
$(".row-centered").css({"background-color": "red"});
}
});

这和一样

您应该使用

if($("html").attr('data-highcontrast-applied')){}

if($("html").data('highcontrast-applied')){}

您可以使用本机javascript来实现

$(document ).ready(function() {
var temp = document.getElementsByTagName("html")[0].getAttribute("data-highcontrast-applied");
console.log("temp==", temp);
if(temp === 'true')
{
$(".row-centered").css({"background-color": "red"});
}
});

https://jsfiddle.net/tyfg6ezv/

您可以尝试使用.addClass((。它很有效。

$(document ).ready(function() {
		var temp = document.getElementsByTagName("html")[0].getAttribute("data-highcontrast-applied");
		if(temp === 'true')
		{
			$(".row-centered").addClass("intro");
		}
	
	});
.intro{
background-color : red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html data-highcontrast-applied="true">
<head>
</head>
<body>
<div class="row-centered">
<p>
Helllllllooooooooooo
</p>
</div>
</body>
</html>

最新更新