1. 程式人生 > >js表格內容比對

js表格內容比對

<html>
<head>
<meta charset="UTF-8">
<title>文件</title>
<style type="text/css">
body{
    width:100%;
}
table{
    width:100%;
    margin-top:20px;
}
input{
    width:100px;
    height:30px;
}
</style>
<script type="text/javascript">
/**
在兩個表格結構相同的情況下:
 
設表1的ID,也就是table標籤的ID為“table1”;
表2的ID為table2;
**/
function testTable(){
    var t1 = document.getElementById('table1');
    var t2 = document.getElementById('table2');
    var tRows = t1.rows.length;
    var tCells = t1.rows[1].cells.length;
    for(var i=1; i<tRows; i++){
        for(var p=0; p<tCells; p++){
            if(t1.rows[i].cells[p].innerHTML != t2.rows[i].cells[p].innerHTML){
                t2.rows[i].cells[p].style.backgroundColor = '#F00';
            }
        }
    }
}
</script>
</head>
 
<body>
<table border="1" cellspacing="0" cellpadding="0" id="table1">
    <tr>
        <th colspan="3">表頭</th>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
</table>
<table border="1" cellspacing="0" cellpadding="0" id="table2">
    <tr>
        <th colspan="3">表頭</th>
    </tr>
    <tr>
        <td>1</td>
        <td>3</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>8</td>
    </tr>
</table>
<input type="button" value="檢測" onClick="testTable()" />
</body>

</html>

題外話:

//第二種方法獲取表格列的內容
用jQuery會方便一些,當然,用原生js也可以
$('tr').each(function(n){ //這裡的n可有可無
//開始遍歷每一行的每一列
for(var i=0;i<cells(3,列數);i++){
$(this).children('td').eq(i).text(); //這裡就拿到了第n行第i列的文字,你可以賦值給其他變數
}

})

用原生js語法:
var table = document.getElementById("mySubjectsTable"); //獲得整個表格物件
for (var i = 0; i < table.rows.length; i++) {
//表格的第i行,第2列
for (var j = 0; j < table.cells.length; j++) {
table.rows[i].cells[j].innerText.trim(" "));
}
}