如果在JavaScript中满足条件,如何循环HTML行并更改背景

时间:2015-01-11 14:34:52

标签: javascript html html5



<body>
  <div id="firsttablediv">
    <table id="firsttable" border="1">
      <thead>
        <th>Item</th>
        <th>Stock</th>
        <th>Minimum Stock</th>
      </thead>
      <tbody id="insertfirsttable">
        <tr>
          <td>Apples</td>
          <td>500</td>
          <td>1000</td>
      </tbody>
    </table>
  </div>
  <button id="check">Check</button>
&#13;
&#13;
&#13;

我希望当我按下检查按钮时,循环遍历所有行并检查库存号是否低于最小库存然后将该行背景更改为红色

2 个答案:

答案 0 :(得分:1)

在vanilla-js,

var rows = document.getElementById('firsttable').tBodies[0].rows;
document.getElementById('check').onclick = function() {
  for(var i=0; i<rows.length; ++i) {
    var stock = +rows[i].cells[1].textContent,
        minStock = +rows[i].cells[2].textContent;
    if(stock < minStock)
      rows[i].classList.add('red');
  }
};

var rows = document.getElementById('firsttable').tBodies[0].rows;
document.getElementById('check').onclick = function() {
  for(var i=0; i<rows.length; ++i) {
    var stock = +rows[i].cells[1].textContent,
        minStock = +rows[i].cells[2].textContent;
    if(stock < minStock)
      rows[i].classList.add('red');
  }
};
.red > td {
  background: red;
}
<table id="firsttable" border="1">
  <thead>
    <th>Item</th>
    <th>Stock</th>
    <th>Minimum Stock</th>
  </thead>
  <tbody id="insertfirsttable">
    <tr>
      <td>Apples</td>
      <td>5000</td>
      <td>1000</td>
    </tr>
    <tr>
      <td>Apples</td>
      <td>500</td>
      <td>1000</td>
    </tr>
  </tbody>
</table>
<button id="check">Check</button>

答案 1 :(得分:0)

你去:

http://jsfiddle.net/cjuaf73e/

你需要为这个解决方案包含jQuery(在我看来,每个webapp都应该有)。

Javascript代码段:

$('#check').click(function(){
    $('#insertfirsttable tr').each(function(){
        var cells = $('td', $(this));
        var stock = parseInt($(cells[1]).text());
        var min = parseInt($(cells[2]).text());
        if (stock < min)
            $(this).addClass('red');
    });
});
希望有所帮助。