jQuery - 如果包含 x 和 y 之间的数字

jQuery - If contains number between x and y

我目前有一个 table,通过 PHP 填充了数字。我想使用 jQuery 检查单元格是否包含介于 1 和 10 之间的数字,然后将 class 应用于该单元格。

这就是我的...

HTML - PHP 填充数字

<table>
  <tr>
    <td class="times"> 11:00</td>
    <td class="number"> 10 </td>
  </tr>
  <tr>
    <td class="times"> 12:00</td>
    <td class="number"> 15 </td>
  </tr>
</table>

jQuery

$( "td.number:contains('10')").addClass( "green" );

这很好用,但我需要它来计算两个数字之间的数字,例如 >=5 && <=10。

知道我该怎么做吗?

使用filter根据某些条件过滤元素。

Reduce the set of matched elements to those that match the selector or pass the function's test.

返回 true 时,元素将添加到集合中,返回 false 时,元素将从集合中删除。

现场演示

$('td.number').filter(function() {
  // Get the number and convert it to Number
  var num = +($(this).text().trim());

  return num >= 5 && num <= 10;
}).addClass('green');
.green {
  color: green;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
  <tr>
    <td class="times">11:00</td>
    <td class="number">10</td>
  </tr>
  <tr>
    <td class="times">12:00</td>
    <td class="number">15</td>
  </tr>
</table>

这个也行JSFiddle

$("td.number").each(function() {
  var inner = $(this).text();
  if (!isNaN(inner) && 0 < inner && inner <= 10) {
    $(this).addClass('green');
  }
  // can add one or more "else if" statements for multi-stage comparison
  // like add more classes or filter out unneeded elements
});
.green {
  color: white;
  font-weight: bold;
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
  <tr>
    <td class="times">11:00</td>
    <td class="number">10</td>
  </tr>
  <tr>
    <td class="times">12:00</td>
    <td class="number">15</td>
  </tr>
</table>

@Tushar 的答案是正确的,因为它只对那些需要操作的元素进行操作。

我只是在可能需要将 class 添加到 每个 td.number 的情况下才添加此方法,基于值在演示中显示。 或者您可以将 'yellow' 替换为 '',它会完成当前的工作。

$('td.number').addClass(function() {
  var n = +this.textContent;
  return (n >= 1 && n <= 10) ? 'green' : 'yellow';
});
.green {
  background-color: green;
}
.yellow {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="times">11:00</td>
    <td class="number">10</td>
  </tr>
  <tr>
    <td class="times">12:00</td>
    <td class="number">15</td>
  </tr>
</table>