2017-08-09 45 views
0

我一直在嘗試使用JavaScript來顯示錶格,並且我想在某些特定條件下更改某個單元格的背景顏色。如何使用JavaScript更改表單個單元格

這裏是我的代碼:

enter image description here

我要的是改變顏色在中間一列只有這樣

This is what i want

然而,它結束了這樣

The whole row is changed

below is my HTML 

     <html> 
<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> 
    <script type="text/javascript" src="wellness.js"></script>  
    <link rel="stylesheet" type="text/css" href="wellness.css"/> 
</head> 
<body> 
    <div class="table-title"> 
     <h3>Wellness Report</h3> 
     <button class = "button search" type = "button" onclick="CreateTableFromJSON()" >Load Data</button> 
    </div> 
    <div id = "showData"></div> 
</body> 
</html> 

請告訴我如何解決它。預先感謝您

+1

你能分享你的HTML代碼嗎? –

+1

你也需要提供一些html。 –

+0

'col'數組裏有什麼? – Airwavezx

回答

0

使用此代碼可以根據您的條件獲取表格的所有單元格的更改值。

var allTableCells = document.getElementsByTagName("td"); 

for(var i = 0, max = allTableCells.length; i < max; i++) { 

    var currentText = allTableCells[i].textContent; 

    // TODO: Change your condition here. 
    if (parseInt(currentText) && parseInt(currentText) > 5) 
     allTableCells[i].style.backgroundColor = "red"; 
} 
0
if (j === 1 && arrItems[1][col[i]] > 5) 
+1

雖然此代碼可能有效,但解釋這個解決方案的方式或原因要好得多。 – ItamarG3

相關問題