2013-01-22 17 views
0

我想遍历表中的行并只执行更改背景颜色如果column2单元格不包含值或空单元格。这是我现在所拥有的,但所有的行都是有颜色的,我只需要在column2中的单元格为空时应用的逻辑。条件逻辑,如果列单元格为空

JS:

// loops through rows 
for (var i = 0; rows; rows = tbody.rows[i]; i++) { 
    //loops through cells 
    for (var j = 1; col; col = rows.cells[j]; j++) { 
     //gets cells of current row 
     cells = rows[i].getElementsByTagName('td'); 
     //gets cells of col 1 
     ocells = rows.cells[j].getElementByTagName('td'); 

     while (rows.cells[j] === null) { 
      //condition here>> 
     } 
    } 
} 

HTML:

<div id="table"> 
    <table name="tbody" id="tbody1"> 
     <tr> 
      <td>col1 Val1</td> 
      <td>col2 Val2</td> 
     </tr> 
     <tr> 
      <td>col1 Val3</td> 
      <td>col2 Val4</td> 
     </tr> 
    </table> 
</div> 

任何帮助,将不胜感激!

+0

安置自己的HTML代码...上面 – ATOzTOA

+0

HTML是寻找一个JavaScript的解决方案。 – charlie

回答

0

我会重新考虑的必要性,循环高于一切要做到这一点:

如果你做的表(或它生成的),加个班每个单元在列2

让我们把这种类: “列-2细胞”

现在使用jQuery:

$('.column-2-cell:empty').addClass('empty'); 

看到这个小提琴:http://jsfiddle.net/Ubz6w/

您也可以选择使用jQuery使用此:

$('tr').each(function(i) { 
    var column2cell = $($(this).children('td')[1]); 
    if (column2cell.text() == "") { 
     column2cell.css('background-color', 'red');   
    } 
}); 

看到这个小提琴:http://jsfiddle.net/Ubz6w/1

希望这有助于!

+0

OP应用 – ATOzTOA

0

只需使用它。这将设置第二个column的背景,如果它是空的。

var tbody = document.getElementsByName("tbody")[0]; 

for (var i = 0, rows; rows = tbody.rows[i]; i++) { 
    if(rows.cells[1].innerHTML == "") { 
     rows.cells[1].className += "highlight"; 
    } 
} 

Live Demo