使用jQuery或JavaScript比较表字符串

Table string compare using jQuery or JavaScript

本文关键字:字符串 比较 JavaScript jQuery 使用      更新时间:2023-09-26

如何使用原生JavaScript或jQuery比较来自两个表的数据?例如,我在同一个HTML页面中有两个表,我想比较这些表中的一些列。例如:列"username"在两个表中都包含一些id,我想突出显示那些"username"列中"first name"answers"last name"列单元格相同的"username"单元格中不具有相同id的"username"单元格。

这里有一个小提琴

<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>

您需要查看每个表格并检查单元格是否不同

$(".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/