我如何在 For/In 循环中使用 parseInt 然后添加 class 来更改 CSS 中的字体颜色?

How do I parseInt in a For/In Loop then add a class to change font color in CSS?

我正在尝试为我工作的曲棍球队创建一个统计数据 table。对于某些类别,我们有特定的指标,例如我们希望投篮 >30 次,但只允许投篮 <25 次;我们希望罚球少于 3 次,但平局多于 3 次,等等。这里是 table,只有 2 场比赛作为输入:

<body>
<header>2019-20 Team Stats</header>
<main>
    <table class="table table-hover">
        <thead>
        <tr>
            <th>Game</th>
            <th>Score</th>
            <th id="goal-f">GF</th>
            <th id="goal-a">GA</th>
            <th id="shot-f">Shots For</th>
            <th id="shot-a">Shots Against</th>
            <th>Shot %</th>
            <th id="pen-t">Pen Taken</th>
            <th id="pen-d">Pen Drawn</th>
            <th>PP %</th>
            <th>PK %</th>
            <th id="fo-p">Face-offs</th>
            <th>Hits</th>
            <th id="blk">BS</th>
            <th id="take-a">TA</th>
            <th id="odd-man">OMA</th>
            <th id="eozp">Extended OZP</th>
            <th id="chance-f">CF</th>
            <th id="chance-a">CA</th>
            <th>Chance +/-</th>
            <th id="turn-o">TO</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>10/11/19 at Boston College</td>
            <td>3-5</td> <!--Score-->
            <td>3</td><!--GF-->
            <td>5</td><!--GA-->
            <td>26</td><!--Shots For-->
            <td>28</td><!--Shots Against-->
            <td>.000</td><!--Shot %-->
            <td class="to-num">5</td><!--Pen Taken-->
            <td>4</td><!--Pen Drawn-->
            <td>33%</td><!--FO%-->
            <td>40%</td><!--PP%-->
            <td>100%</td><!--PK%-->
            <td>9</td><!--Hits-->
            <td>11</td><!--BS-->
            <td>7</td><!--TA-->
            <td>10</td><!--OMA-->
            <td>0</td><!--OZP-->
            <td>13</td><!--CF-->
            <td>17</td><!--CA-->
            <td>-4</td><!--C +/1-->
            <td>12</td><!--TO-->
        </tr>
        <tr>
            <td>10/12/19 at Merrimack</td>
            <td>11-6</td> <!--Score-->
            <td>11</td><!--GF-->
            <td>6</td><!--GA-->
            <td>26</td><!--Shots For-->
            <td>22</td><!--Shots Against-->
            <td>.000</td><!--Shot %-->
            <td>3</td><!--Pen Taken-->
            <td>6</td><!--Pen Drawn-->
            <td>64%</td><!--FO%-->
            <td>50%</td><!--PP%-->
            <td>100%</td><!--PK%-->
            <td>9</td><!--Hits-->
            <td>14</td><!--BS-->
            <td>6</td><!--TA-->
            <td>11</td><!--OMA-->
            <td>2</td><!--OZP-->
            <td>22</td><!--CF-->
            <td>14</td><!--CA-->
            <td>+8</td><!--C +/1-->
            <td>18</td><!--TO-->
        </tr>
        </tbody>
    </table>
</main>

本质上,我尝试将 .to-num class 从字符串解析为整数,然后如果该整数为 < 或 > 3,则添加 'negative' 或 'positive' class,然后会将字体颜色从黑色更改为红色或绿色。

for (var i = 0; i < $(".to-num").length; i++) {
var outcome = parseInt($(".to-num")[i]);
if (outcome > 3) {
    $(".to-num").addClass("negative");
} else if (outcome < 3) {
    $(".to-num").addClass("positive");
}

}

这是我的 HTML、CSS 和 JS 的 CodePen:https://codepen.io/emilyengelnatzke/pen/qBNOQZe

您需要在同一元素上重新设置 class。实际上,您每次都在所有元素上设置 class 。此外,您需要在 parse

之前调用 innerText 或 textContent

你可以这样做:

$(".to-num").each(function() {
  var outcome = parseInt(this.innerText);
if (outcome > 3) {
    this.classList.add("negative");
} else if (outcome < 3) {
    this.classList.add("positive");
}
});

最简单的实现方法如下:

// select all elements with the class-name of 'to-num', and
// call jQuery's addClass() method on each element of that
// collection:
$('.to-num').addClass(function() {

  // here we return a class-name as a result of this conditional
  // operator; if the parsed-value of the current element's text
  // is greater than 3 we return the 'negative' class-name,
  // otherwise we return 'positive':
  return parseInt($(this).text().trim(), 10) > 3 ? 'negative' : 'positive';
});

$('.to-num').addClass(function() {
  return parseInt($(this).text().trim(), 10) > 3 ? 'negative' : 'positive';
});
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

table {
  border-collapse: collapse;
}

tbody tr:nth-child(odd) {
  background-color: #dde;
}

th,
td {
  background-color: transparent;
}

td.negative {
  color: red;
}

td.positive {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <h1>2019-20 Team Stats</h1>
</header>
<main>
  <table class="table table-hover">
    <thead>
      <tr>
        <th>Game</th>
        <th>Score</th>
        <th id="goal-f">GF</th>
        <th id="goal-a">GA</th>
        <th id="shot-f">Shots For</th>
        <th id="shot-a">Shots Against</th>
        <th>Shot %</th>
        <th id="pen-t">Pen Taken</th>
        <th id="pen-d">Pen Drawn</th>
        <th>PP %</th>
        <th>PK %</th>
        <th id="fo-p">Face-offs</th>
        <th>Hits</th>
        <th id="blk">BS</th>
        <th id="take-a">TA</th>
        <th id="odd-man">OMA</th>
        <th id="eozp">Extended OZP</th>
        <th id="chance-f">CF</th>
        <th id="chance-a">CA</th>
        <th>Chance +/-</th>
        <th id="turn-o">TO</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><time date="2019-10-11">10/11/19</time>
          <span class="location">Boston College</span></td>
        <td>3-5</td>
        <!--Score-->
        <td>3</td>
        <!--GF-->
        <td>5</td>
        <!--GA-->
        <td>26</td>
        <!--Shots For-->
        <td>28</td>
        <!--Shots Against-->
        <td>.000</td>
        <!--Shot %-->
        <td class="to-num">5</td>
        <!--Pen Taken-->
        <td>4</td>
        <!--Pen Drawn-->
        <td>33%</td>
        <!--FO%-->
        <td>40%</td>
        <!--PP%-->
        <td>100%</td>
        <!--PK%-->
        <td>9</td>
        <!--Hits-->
        <td>11</td>
        <!--BS-->
        <td>7</td>
        <!--TA-->
        <td>10</td>
        <!--OMA-->
        <td>0</td>
        <!--OZP-->
        <td>13</td>
        <!--CF-->
        <td>17</td>
        <!--CA-->
        <td>-4</td>
        <!--C +/1-->
        <td>12</td>
        <!--TO-->
      </tr>
      <tr>
        <td><time date="2019-10-12">10/12/19</time>
          <span class="location">Merrimack</span></td>
        <td>11-6</td>
        <!--Score-->
        <td>11</td>
        <!--GF-->
        <td>6</td>
        <!--GA-->
        <td>26</td>
        <!--Shots For-->
        <td>22</td>
        <!--Shots Against-->
        <td>.000</td>
        <!--Shot %-->
        <td class="to-num">3</td>
        <!--Pen Taken-->
        <td>6</td>
        <!--Pen Drawn-->
        <td>64%</td>
        <!--FO%-->
        <td>50%</td>
        <!--PP%-->
        <td>100%</td>
        <!--PK%-->
        <td>9</td>
        <!--Hits-->
        <td>14</td>
        <!--BS-->
        <td>6</td>
        <!--TA-->
        <td>11</td>
        <!--OMA-->
        <td>2</td>
        <!--OZP-->
        <td>22</td>
        <!--CF-->
        <td>14</td>
        <!--CA-->
        <td>+8</td>
        <!--C +/1-->
        <td>18</td>
        <!--TO-->
      </tr>
    </tbody>
  </table>
</main>

当然,我们可以使用普通 JavaScript:

轻松实现相同的结果
// caching all elements in the document that include the class-name
// of 'to-num':
const collection = document.querySelectorAll('.to-num'),

      // defining a named function to handle the addition of
      // relevant class-names; the first three arguments
      // ('el', 'index', 'arr') are passed automatically from
      // the use of NodeList.prototype.forEach(); here we also
      // declare the argument 'gt' ('greater-than') with a
      // default value of 3 (which can be overridden by the
      // author/user):
      isGreaterThan = (el, index, arr, gt = 3) => {

        // here we use the same conditional operator as above to
        // determine which of the two class-names to use:
        let newClass = parseInt(el.textContent.trim(), 10) > gt ? 'negative' : 'positive';

    // and here we use the Element.classList API to add that
    // class-name to the current element-node of the NodeList
    // over which we're iterating:
    el.classList.add(newClass);
  };

// using NodeList.prototype.forEach() to iterate over the
// NodeList we cached earlier, calling the isGreaterThan()
// function on all elements in the NodeList:
collection.forEach(isGreaterThan);

const collection = document.querySelectorAll('.to-num'),
  isGreaterThan = (el, index, arr, gt = 3) => {
    let newClass = parseInt(el.textContent.trim(), 10) > gt ? 'negative' : 'positive';
    el.classList.add(newClass);
  };

collection.forEach(isGreaterThan);
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

table {
  border-collapse: collapse;
}

tbody tr:nth-child(odd) {
  background-color: #dde;
}

th,
td {
  background-color: transparent;
}

td.negative {
  color: red;
}

td.positive {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <h1>2019-20 Team Stats</h1>
</header>
<main>
  <table class="table table-hover">
    <thead>
      <tr>
        <th>Game</th>
        <th>Score</th>
        <th id="goal-f">GF</th>
        <th id="goal-a">GA</th>
        <th id="shot-f">Shots For</th>
        <th id="shot-a">Shots Against</th>
        <th>Shot %</th>
        <th id="pen-t">Pen Taken</th>
        <th id="pen-d">Pen Drawn</th>
        <th>PP %</th>
        <th>PK %</th>
        <th id="fo-p">Face-offs</th>
        <th>Hits</th>
        <th id="blk">BS</th>
        <th id="take-a">TA</th>
        <th id="odd-man">OMA</th>
        <th id="eozp">Extended OZP</th>
        <th id="chance-f">CF</th>
        <th id="chance-a">CA</th>
        <th>Chance +/-</th>
        <th id="turn-o">TO</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><time date="2019-10-11">10/11/19</time>
          <span class="location">Boston College</span></td>
        <td>3-5</td>
        <!--Score-->
        <td>3</td>
        <!--GF-->
        <td>5</td>
        <!--GA-->
        <td>26</td>
        <!--Shots For-->
        <td>28</td>
        <!--Shots Against-->
        <td>.000</td>
        <!--Shot %-->
        <td class="to-num">5</td>
        <!--Pen Taken-->
        <td>4</td>
        <!--Pen Drawn-->
        <td>33%</td>
        <!--FO%-->
        <td>40%</td>
        <!--PP%-->
        <td>100%</td>
        <!--PK%-->
        <td>9</td>
        <!--Hits-->
        <td>11</td>
        <!--BS-->
        <td>7</td>
        <!--TA-->
        <td>10</td>
        <!--OMA-->
        <td>0</td>
        <!--OZP-->
        <td>13</td>
        <!--CF-->
        <td>17</td>
        <!--CA-->
        <td>-4</td>
        <!--C +/1-->
        <td>12</td>
        <!--TO-->
      </tr>
      <tr>
        <td><time date="2019-10-12">10/12/19</time>
          <span class="location">Merrimack</span></td>
        <td>11-6</td>
        <!--Score-->
        <td>11</td>
        <!--GF-->
        <td>6</td>
        <!--GA-->
        <td>26</td>
        <!--Shots For-->
        <td>22</td>
        <!--Shots Against-->
        <td>.000</td>
        <!--Shot %-->
        <td class="to-num">3</td>
        <!--Pen Taken-->
        <td>6</td>
        <!--Pen Drawn-->
        <td>64%</td>
        <!--FO%-->
        <td>50%</td>
        <!--PP%-->
        <td>100%</td>
        <!--PK%-->
        <td>9</td>
        <!--Hits-->
        <td>14</td>
        <!--BS-->
        <td>6</td>
        <!--TA-->
        <td>11</td>
        <!--OMA-->
        <td>2</td>
        <!--OZP-->
        <td>22</td>
        <!--CF-->
        <td>14</td>
        <!--CA-->
        <td>+8</td>
        <!--C +/1-->
        <td>18</td>
        <!--TO-->
      </tr>
    </tbody>
  </table>
</main>

...As a follow up questions, would I need to repeat that for each category? I.e "shots for", "shots against", etc.? Or is there more of a global option?

.

关于上面的评论,我只是添加了一些自定义的 data-* 属性,在本例中可能是 data-boundary 以及 data-abovedata-below 来标识class-names 如果单元格的值高于或低于该边界则应用;例如:

// here we select all <th> elements with the 'data-boundary'
// attribute, and use the each() method to iterate over that
// collection:
$('th[data-boundary]').each(function(index, elem) {

  // here we use a mostly native JavaScript approach for
  // simplicity; the boundary we find by first using the
  // Element.dataset API to retrieve the value of the
  // data-boundary attribute, that is passed into the
  // parseInt() function (along with the radix of 10, to
  // ensure a base-10/decimal number); if parsing results
  // in a false/falsey value we instead use 0 (zero is itself
  // a falsey value, so this is a mild sanity-check for that
  // result):
  const boundary = parseInt(elem.dataset.boundary.trim(), 10) || 0,

    // we use the Element.dataset API to retrieve the relevant
    // class-names:
    aboveClass = elem.dataset.above,
    belowClass = elem.dataset.below,

    // we retrieve the cellIndex of the current element
    // (note that this can be problematic if the `colspan`
    // attribute is used) from the HTMLTableHeaderCellElement
    // (also available to HTMLTableCellElement nodes):
    column = elem.cellIndex,

    // here we use jQuery - although document.querySelectorAll
    // could have been used just as easily - to retrieve all
    // <td> elements that match the :nth-child() pseudo-class
    // selector within <tr> elements and within the <tbody>
    // element; we use 'column + 1' because JavaScript is
    // zero-based whereas CSS is 1-based; note that we're also
    // wrapping this CSS selector in a template-literal string
    // in order to avoid string-concatenation with the
    // variable, here we simply use the variable within the
    // string inside of a '${ ...JavaScript here... }':
    cells = $(`tbody tr td:nth-child(${ column + 1 })`);

  // we iterate over the cells here as we did in our first
  // example:
  cells.addClass(function() {
    return parseInt(this.textContent.trim(), 10) > boundary ? aboveClass : belowClass;
  });
});

$('th[data-boundary]').each(function(index, elem) {
  const boundary = parseInt(elem.dataset.boundary.trim(), 10) || 0,
    aboveClass = elem.dataset.above,
    belowClass = elem.dataset.below,
    column = elem.cellIndex,
    cells = $(`tbody tr td:nth-child(${ column + 1 })`);
  cells.addClass(function() {
    return parseInt(this.textContent.trim(), 10) > boundary ? aboveClass : belowClass;
  });
});
*,
 ::before,
 ::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

table {
  border-collapse: collapse;
}

tbody tr:nth-child(odd) {
  background-color: #dde;
}

th,
td {
  background-color: transparent;
}

td.negative {
  color: red;
}

td.positive {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <h1>2019-20 Team Stats</h1>
</header>
<main>
  <table class="table table-hover">
    <thead>
      <tr>
        <th>Game</th>
        <th>Score</th>
        <th id="goal-f">GF</th>
        <th id="goal-a">GA</th>
        <th id="shot-f" data-boundary="30" data-above="positive" data-below="negative">Shots For</th>
        <th id="shot-a" data-boundary="25" data-above="negative" data-below="positive">Shots Against</th>
        <th>Shot %</th>
        <th id="pen-t" data-boundary="3" data-above="negative" data-below="positive">Pen Taken</th>
        <th id="pen-d">Pen Drawn</th>
        <th>PP %</th>
        <th>PK %</th>
        <th id="fo-p">Face-offs</th>
        <th>Hits</th>
        <th id="blk">BS</th>
        <th id="take-a">TA</th>
        <th id="odd-man">OMA</th>
        <th id="eozp">Extended OZP</th>
        <th id="chance-f">CF</th>
        <th id="chance-a">CA</th>
        <th>Chance +/-</th>
        <th id="turn-o">TO</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><time date="2019-10-11">10/11/19</time>
          <span class="location">Boston College</span></td>
        <td>3-5</td>
        <!--Score-->
        <td>3</td>
        <!--GF-->
        <td>5</td>
        <!--GA-->
        <td>26</td>
        <!--Shots For-->
        <td>28</td>
        <!--Shots Against-->
        <td>.000</td>
        <!--Shot %-->
        <td class="to-num">5</td>
        <!--Pen Taken-->
        <td>4</td>
        <!--Pen Drawn-->
        <td>33%</td>
        <!--FO%-->
        <td>40%</td>
        <!--PP%-->
        <td>100%</td>
        <!--PK%-->
        <td>9</td>
        <!--Hits-->
        <td>11</td>
        <!--BS-->
        <td>7</td>
        <!--TA-->
        <td>10</td>
        <!--OMA-->
        <td>0</td>
        <!--OZP-->
        <td>13</td>
        <!--CF-->
        <td>17</td>
        <!--CA-->
        <td>-4</td>
        <!--C +/1-->
        <td>12</td>
        <!--TO-->
      </tr>
      <tr>
        <td><time date="2019-10-12">10/12/19</time>
          <span class="location">Merrimack</span></td>
        <td>11-6</td>
        <!--Score-->
        <td>11</td>
        <!--GF-->
        <td>6</td>
        <!--GA-->
        <td>26</td>
        <!--Shots For-->
        <td>22</td>
        <!--Shots Against-->
        <td>.000</td>
        <!--Shot %-->
        <td class="to-num">3</td>
        <!--Pen Taken-->
        <td>6</td>
        <!--Pen Drawn-->
        <td>64%</td>
        <!--FO%-->
        <td>50%</td>
        <!--PP%-->
        <td>100%</td>
        <!--PK%-->
        <td>9</td>
        <!--Hits-->
        <td>14</td>
        <!--BS-->
        <td>6</td>
        <!--TA-->
        <td>11</td>
        <!--OMA-->
        <td>2</td>
        <!--OZP-->
        <td>22</td>
        <!--CF-->
        <td>14</td>
        <!--CA-->
        <td>+8</td>
        <!--C +/1-->
        <td>18</td>
        <!--TO-->
      </tr>
    </tbody>
  </table>
</main>

参考文献: