如果其他问题,则使用Javascript

Javascript if else issue

本文关键字:Javascript 其他 问题 如果      更新时间:2023-09-26

我有一个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';
}

您将元素视为数字。您希望检索元素的内容并将其转换为数字。

var testDivValue = parseInt(testDiv.textContent, 10);

您试图检查元素的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';
}

您已经将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");
    }

我希望你觉得这个有用,

谢谢。