使用 Javascript 显示 HTML 表中两个单元格之间的差异

Use Javascript to show the difference between two cells in an HTML table

本文关键字:单元格 两个 之间 显示 Javascript HTML 使用      更新时间:2023-09-26

这一定很简单,但我对JS还很陌生,找不到解决方案。假设我有这个表:

<table class="mytable">
   <tbody>
      <tr>
         <th>Price A</th>
         <th>Price B</th>
         <th>Up/Down Amount</th>
      </tr>
      <tr>
         <td>23.5</td>
         <td>90.6</td>
         <td>Difference</td>
      </tr>
   </tbody>
</table>
  1. 我如何让 JS 显示价格 A 和价格 B 之间的差异,并根据 B 是高还是低将其着色为红色或绿色?

  2. 如果其中一个数值是由简码(wordpress)生成的,我如何让JS解析它?我已经尝试过$(window).on("load", function(){ ..但它在我测试过的其他表上不起作用*

    • 这个表的小提琴(基于值低于另一个单元格的颜色单元格)它在这里工作,但我根本无法让它在 Wordpress 中发挥作用。

任何帮助将不胜感激。

jQuery:

$(".mytable tr").not(":first").each(function() {
    var td1 = parseFloat($(this).children("td.pricea").text()),
        td2 = parseFloat($(this).children("td.priceb").text()),
        difference = (td1 - td2),
        absNum = Math.abs(difference),
        largerNum = td1 > td2 ? td1 : td2,
        percentage = ((absNum / largerNum) * 100).toFixed(2);
    if (difference < 0)
       $(this).children("td.out").text(percentage).addClass("green");
    else
        $(this).children("td.out").text(percentage).addClass("red");
});

.CSS:

table td {padding: 5px;}
.green {
    background-color: #C8FDD3;
}
.red {
    background-color: #FDC8C8;
}
.pricea:before {
   content: "$";
}
.priceb:before {
   content: "$";
}
.out:after {
   content: "%";
}

js小提琴

要获得 2 个数字的差值百分比,您需要取差值,将其除以更大的数字,然后乘以 100。

如果这回答了您的问题,请将其标记为答案。

请在此处观看演示

$(".colorMe tr").each(function() {
    if (($(this).find("td:eq(0)").text()-$(this).find("td:eq(1)").text())>0)
    {
            $(this).css("background","red");
    }
    else{
    $(this).css("background","green");
    }
});
$(document).ready(function() {
    $(".mytable").find("tr").each(function() {
        var price_a = parseFloat($(this).find("td:nth-child(1)").text());
        var price_b = parseFloat($(this).find("td:nth-child(2)").text());
        var diff = price_a - price_b;
        var $res = $(this).find("td:nth-child(3)");
        $res.text(diff);
        if (diff < 0) {
            $res.css("backgroundColor", "red");
        } else {
            $res.css("backgroundColor", "green");
        }
    });
});

在window.onload或任何其他事件上调用此函数,请检查此演示小提琴

function cal()
{
 var ele = document.getElementsByTagName('tr');
 for(var i=0;i<ele.length;i++)
 {
   var tds = ele[i].getElementsByTagName('td');
     var td1 = parseInt(tds[0].innerHTML);
     var td2 = parseInt(tds[1].innerHTML);
     tds[2].innerHTML = td2-td1;
     if(td1>td2)
     tds[0].style.backgroundColor = "green";
     else
     tds[1].style.backgroundColor = "green";
 }
}