js能否实现一个数字自动添加背景的,比如js里设置01的背景色是红色,那么html的01就是红色背景。js里02是蓝色,那么html的02就是蓝色背景。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title> 页面名称 </title>
</head>
<body>
<div id="box">
<div>01</div>
<div>02</div>
<div>03</div>
<div>01</div>
<div>02</div>
</div>
<script type="text/javascript">
var obj = {"01":"red","02":"blue","03":"green"};
var div = document.querySelectorAll("#box div");
div.forEach(function(v, i){
v.style.backgroundColor = obj[v.innerHTML];
});
</script>
</body>
</html>
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
直接用class[attribute*=value] 选择器,只要属性中有该value,则使用这个class。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div[class*="01"]
{
background:#ffff00;
}
div[class*="02"]
{
background:#ff0000;
}
</style>
</head>
<body>
<div class="first_test01">这是第一个 div 元素。</div>
<div class="second ccc02ccc">这是第二个 div 元素。</div>
<div class="test">这是第三个 div 元素。</div>
<p class="test">这是段落中的文本。</p>
</body>
</html>