2015-02-05 53 views
0

我有一個div,我想根據div中的int值更改顏色,但由於某些原因,它不會根據我寫的if else語句更改顏色。而不會出現顏色。這是爲什麼?Javascript if if問題

<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'; 
} 
+2

爲什麼'testDiv'是數字,或以任何方式相當於一個數字,它顯然是一個元素 – adeneo 2015-02-05 22:51:17

+0

你可能想'parseInt函數(testDiv.innerHTML,10)' – adeneo 2015-02-05 22:52:44

回答

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'; 
} 
4

你治療像數的元素。您想要檢索元素的內容並將其轉換爲數字。

var testDivValue = parseInt(testDiv.textContent, 10); 
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"); 
    } 

我希望你發現這很有用,

感謝。