2015-08-28 39 views
3

如何使用原生JavaScript或jQuery比較兩個表中的數據? 例如,我在同一個HTML頁面中有兩個表格,我想比較這些表格中的幾列。 例如:列「用戶名」包含這兩個表中的一些ID,我想突出顯示那些「名字」和「姓氏」列單元格的「用戶名」列上沒有相同標識的那些「用戶名」單元格相同。使用jQuery或JavaScript進行表字符串比較

here is a small fiddle

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> 
 
<div class="container"> 
 
    <table class="table"> 
 
     <caption>Table One</caption> 
 
     <thead> 
 
     <tr> 
 
      <th>#</th> 
 
      <th>First Name</th> 
 
      <th>Last Name</th> 
 
      <th>Username</th> 
 
     </tr> 
 
     </thead> 
 
     <tbody> 
 
     <tr> 
 
      <th scope="row">1</th> 
 
      <td>Mark</td> 
 
      <td>Otto</td> 
 
      <td>7872</td> 
 
     </tr> 
 
     <tr> 
 
      <th scope="row">2</th> 
 
      <td>Jacob</td> 
 
      <td>Thornton</td> 
 
      <td>9890</td> 
 
     </tr> 
 
     <tr> 
 
      <th scope="row">3</th> 
 
      <td>Larry</td> 
 
      <td>the Bird</td> 
 
      <td>7719</td> 
 
     </tr> 
 
     </tbody> 
 
    </table> 
 
</div> 
 

 
<div class="container"> 
 
    <table class="table"> 
 
     <caption>Table Two</caption> 
 
     <thead> 
 
     <tr> 
 
      <th>#</th> 
 
      <th>First Name</th> 
 
      <th>Last Name</th> 
 
      <th>Username</th> 
 
     </tr> 
 
     </thead> 
 
     <tbody> 
 
     <tr> 
 
      <th scope="row">1</th> 
 
      <td>Mark</td> 
 
      <td>Otto</td> 
 
      <td>7872</td> 
 
     </tr> 
 
     <tr> 
 
      <th scope="row">2</th> 
 
      <td>Jacob</td> 
 
      <td>Thornton</td> 
 
      <td>2232</td> 
 
     </tr> 
 
     <tr> 
 
      <th scope="row">3</th> 
 
      <td>Larry</td> 
 
      <td>the Bird</td> 
 
      <td>7719</td> 
 
     </tr> 
 
     </tbody> 
 
    </table> 
 
</div>

回答

3

,需要在每個表,並檢查是否細胞型動物

$(".table:first tbody tr").each(function(){ 
    var tabletr=$(this); 
    var tableone=$(this).children("td"); 
    $(".table:last tbody tr").each(function(){ 
     if(tableone.eq(0).text()== $(this).children("td").eq(0).text() && tableone.eq(1).text()== $(this).children("td").eq(1).text() && tableone.eq(2).text()!= $(this).children("td").eq(2).text()){ 
      tabletr.css("background","#f00"); 
      $(this).css("background","#f00"); 
     console.log("USERNAME DIFFERENT!"+$(this).children("td").eq(2).text()); 
     } 
    }); 
}); 

https://jsfiddle.net/DTcHh/11529/

+1

哇ŧ他很好,如果太棒了!讓我測試一下 – BurebistaRuler