如何在For / In循环中parseInt然后添加一个类以更改CSS中的字体颜色?

如何解决如何在For / In循环中parseInt然后添加一个类以更改CSS中的字体颜色?

我正在为与我合作的曲棍球队创建一个统计表。我们有某些指标想要针对某些类别进行打击,例如我们想拍摄30张以上的镜头,但只允许拍摄25张以下的镜头;我们希望罚分少于3,但罚分大于3,依此类推。这是只有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类从字符串解析为整数,然后如果该整数是 3,则添加“负”或“正”类,然后将其更改字体颜色从黑色到红色或绿色。

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

解决方法

您需要将类重新设置为相同的元素。实际上,您每次都在所有元素上设置类。另外,在解析之前,您需要调用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,gt = 3) => {
    let newClass = parseInt(el.textContent.trim(),10) > gt ? 'negative' : 'positive';
    el.classList.add(newClass);
  };

collection.forEach(isGreaterThan);
*,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>

...作为后续问题,我需要针对每个类别重复一下吗?即“投篮”,“投篮”等?还是有更多的全球选择?

OP's comment to another answer

关于上述评论,我只添加一些自定义data-*属性,在这种情况下,可能将data-boundary连同data-abovedata-below一起来标识该类-如果单元格的值在该边界之上或之下,则要应用的名称;例如:

// 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(),aboveClass = elem.dataset.above,column = elem.cellIndex,cells = $(`tbody tr td:nth-child(${ column + 1 })`);
  cells.addClass(function() {
    return parseInt(this.textContent.trim(),10) > boundary ? aboveClass : belowClass;
  });
});
*,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>

参考:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res