比较表格单元格的两个值如果相同则添加类

时间:2017-07-18 02:57:43

标签: javascript jquery twitter-bootstrap twitter-bootstrap-3

我现在比较两个单元格值有问题。在我使用onclick函数获取特定单元格值之前。因此我可以很容易地比较两个项目,但现在我需要自动比较两个项目并添加bootstrap类成功,如果它们是相同的。我现在使用的代码如下所示。

JSFIDDLE:https://jsfiddle.net/aice09/ynh8wfc9/

var tables = document.getElementsByClassName('tb_jobsched');
var rows = tables[0].getElementsByTagName('tr');

var data = tables.row($(this).parents('tr')).data();
var poqty = data[5];
var stock= data[7];

var newpoqty = poqty .replace("PCS", "");
var newstocks = stock.replace("PCS", "");

if (newpoqty === newstocks) {
  rows[i].classList.add("success");
} else {

}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<table id="tb_jobsched" class="table table-bordered table-hover">
  <thead>
    <tr>
      <td>CUSTOMER</td>
      <td>PO QUANTITY</td>
      <td>DATE OF DELIVERY</td>
      <td>STOCKS</td>
    </tr>
  </thead>
  <tr>
    <td>CUSTOMER 1</td>
    <td>2000 PCS</td>
    <td>2017/06/15</td>
    <td>5000 PCS</td>
  </tr>
  <tr>
    <td>CUSTOMER 2</td>
    <td>500 PCS</td>
    <td>2017/06/15</td>
    <td>500 PCS</td>
  </tr>
</table>

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
tf.TextLineReader
&#13;
const rows = document.querySelectorAll('#myTable tbody tr');

rows.forEach((row) => {
	const cells = row.getElementsByTagName('td');
  const poQty = cells[1].innerText;
  const stocks = cells[3].innerText;
  
  if (poQty === stocks) {
  	row.classList.add('success');
  }
});
&#13;
.success {
  background: green;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

var tables = document.getElementsByClassName('tb_jobsched');
var rows = tables[0].getElementsByTagName('tr');

for(var i = 0; i< rows.length; i++) {
	var childs = rows[i].getElementsByTagName('td');
  var potqty = childs[1].innerHTML.replace('PCS', '');
  var stock = childs[3].innerHTML.replace('PCS', '');
  if(potqty === stock) {
  	rows[i].className += 'success';
  }
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<table id="myTable" class="table table-bordered table-hover">
  <thead>
    <tr>
      <td>CUSTOMER</td>
      <td>PO QUANTITY</td>
      <td>DATE OF DELIVERY</td>
      <td>STOCKS</td>
    </tr>
  </thead>
  <tbody class="tb_jobsched">
    <tr>
      <td>CUSTOMER 1</td>
      <td>2000 PCS</td>
      <td>2017/06/15</td>
      <td>5000 PCS</td>
    </tr>
    <tr>
      <td>CUSTOMER 2</td>
      <td>500 PCS</td>
      <td>2017/06/15</td>
      <td>500 PCS</td>
    </tr>
  </tbody>
</table>