我应该如何编写Javascript以根据我显示的数字向我的ID polIndice添加新类(.indiceLow,indiceMedium,indiceHigh)。
它们应该显示如下:
.indice {
background-color:#F5F5F5;
width: 50%;
text-align:center;
padding:10px;
}
.indiceLow {
background-color: #BBCF4C;
color:#fff;
}
.indiceMedium {
background-color: #EEC20B;
color:#fff;
}
.indiceHigh {
background-color: #F29305;
color:#fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="polIndice" class="indice">(number)</div>
</body>
</html>
&#13;
感谢您的帮助
答案 0 :(得分:0)
您只需要innerHTML/innerText
方法和一组条件。不需要jQuery。
var el = document.getElementById('polIndice');
var val = parseInt(el.innerText);
var class_name;
if (val < 50) {
class_name = 'indiceLow';
} else if (val < 100) {
class_name = 'indiceMedium';
} else {
class_name = 'indiceHigh';
}
el.className += ' ' + class_name;
答案 1 :(得分:0)
我为你创造了一个功能,但我认为你真的不需要这个...
function addIndice(elemId, num) {
var classNam = ['indiceLow', 'indiceMedium', 'indiceHigh'];
num = typeof(num) == "number" ? num : parseInt(num);
var elem = document.getElementById(elemId);
if(num < 50) {
elem.className += " " + classNam[0];
}else if(num >= 50 && num <= 100) {
elem.className += " " + classNam[1];
}else if(num > 100) {
elem.className += " " + classNam[2];
}
}
使用HTML文件:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
.indice {
background-color:#F5F5F5;
width: 50%;
text-align:center;
padding:10px;
}
.indiceLow {
background-color: #BBCF4C;
color:#fff;
}
.indiceMedium {
background-color: #EEC20B;
color:#fff;
}
.indiceHigh {
background-color: #F29305;
color:#fff;
}
</style>
</head>
<body>
<div id="polIndice" class="indice"></div>
<!-- Script at the end -->
<script type="text/javascript" >
function addIndice(elemId, num) {
var classNam = ['indiceLow', 'indiceMedium', 'indiceHigh'];
num = typeof(num) == "number" ? num : parseInt(num);
var elem = document.getElementById(elemId);
if(num < 50) {
elem.className += " " + classNam[0];
}else if(num >= 50 && num <= 100) {
elem.className += " " + classNam[1];
}else if(num > 100) {
elem.className += " " + classNam[2];
}
}
addIndice('polIndice', 10);
</script>
</body>
</html>