我有一个div,我想根据div中的int值更改颜色,但由于某种原因,它不会根据我写的if else语句更改颜色。相反,没有颜色出现。那是为什么?
<div id="test">66</div>
JAVASCRIPT
var testDiv = document.getElementById("test");
if (testDiv<50) {
testDiv.style.backgroundColor = '#900000';
} else if (testDiv > 49 && testDiv < 75) {
testDiv.style.backgroundColor = '#FF9933';
} else if (testDiv > 74) {
testDiv.style.backgroundColor = '#00CC00';
}
答案 0 :(得分:4)
您将元素视为数字。您想要检索元素的内容并将其转换为数字。
var testDivValue = parseInt(testDiv.textContent, 10);
答案 1 :(得分:1)
您正在尝试检查元素的innerHTML,但要与元素本身进行比较。尝试:
var testDiv = document.getElementById("test");
var value = parseInt(testDiv.innerHTML);
if(value<50){
testDiv.style.backgroundColor = '#900000';
}
else if(value>49 && value <75){
testDiv.style.backgroundColor = '#FF9933';
}
else if(value>74){
testDiv.style.backgroundColor = '#00CC00';
}
答案 2 :(得分:0)
您已将HTML对象传递给if语句,而不是它的实际值。您可以使用 innerHTML 属性来获取HTML元素中的内容。
var test = document.getElementById("test"); // element by id
var testContent = test.innerHTML; // the value of inner HTML content
将值存储在testContent变量中后,您可以随意执行任何操作; - )
// Check if value of inner HTML is less than 50
if(testContent < 50) {
alert("true, do whatever you want.");
} else {
alert("false");
}
我希望你觉得这很有用,
感谢。