【问题标题】:Javascript update to HTML table cell (from thousands to millions)Javascript 更新到 HTML 表格单元格(从数千到数百万)
【发布时间】:2017-01-19 06:11:58
【问题描述】:

我需要在我的网络报告上创建一些 Javascript,将表格值转换为数千或数百万(例如除以或乘以 1000)。

问题在于每个值都是“可点击的”(即,它被包裹在一个锚标记中)。

这可能吗?

<table class="Table" >
<thead><tr>
  <th class="l Header" scope="col">£000s</th>
  <th class="l Header" scope="col">Col1</th>
  <th class="l Header" scope="col">Col2</th>
</tr></thead>
<tbody>
<tr>
  <td class="l Data">   My Data Row </td>
  <td class="l Data">   <a class=nums href="javascript:MyFunc();">  11,372,397</a></td>
  <td class="l Data">   <a class=nums href="javascript:MyFunc();">  11,344,327</a></td>
</tr>
</tbody>

编辑

我正在使用 IE6。基本上目标是有一个“千”和一个“百万”按钮,以便表格的值可以变为 11,372k 或 11.4m 等...

【问题讨论】:

  • 我不明白你的问题,你能详细点吗
  • 我很想对你提到的 ie6 投反对票 :-(
  • "我使用的是 IE6。"你是叛徒。
  • 大声笑 - 我们真的别无选择! IE6是公司标准!!

标签: javascript html css html-table


【解决方案1】:

我会使用jQuery

$(function (){
    $.each($('.nums'), function () {
        $(this).html(Number($(this).html().replace(/,/g,"")) /*your math here*/);
    });
});

针对您的编辑: 由于我很无聊,所以我为您编写了这段工作代码,根据您的需要舍入并插入“,”。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<table class="Table" >
<thead><tr>
  <th class="l Header" scope="col">£000s</th>
  <th class="l Header" scope="col">Col1</th>
  <th class="l Header" scope="col">Col2</th>
</tr></thead>
<tbody>
<tr>
  <td class="l Data">   My Data Row </td>
  <td class="l Data">   <a class="nums" href="javascript:MyFunc();">  11,372,397</a></td>
  <td class="l Data">   <a class="nums" href="javascript:MyFunc();">  11,344,327</a></td>
</tr>
</tbody>

<input type="button" onclick="toMillions();"> 
<input type="button" onclick="restore();"> 

<script type="text/javascript">

    $(function (){
        $.each($('.nums'), function () {
            $.data(this, "theValue", $(this).html());
        }); 
    });


    function toMillions(){
        $.each($('.nums'), function () {
            $(this).html(Number($.data(this,"theValue").replace(/,/g,"")) / 1000000 + ' million');
        });
    }

    function restore(){
        $.each($('.nums'), function () {
                $(this).html($.data(this,"theValue"));
        });
    }
</script>

【讨论】:

  • 非常感谢 Odge - 我会在星期一看看这个。快速的问题 - 这段代码在没有互联网连接的情况下可以工作吗?我也需要代码在离线模式下工作..
  • 您必须以另一种方式提供 jQuery JS,但它应该可以工作。
【解决方案2】:

我会开始考虑 document.getElementsByClassName('nums'),它会为您提供一个元素数组。像这样的:

nums = document.getElementsByClassName('nums');
for (i in nums)
   nums[i].innerHTML = nums[i]+',000';i

不过,这可能仅适用于较新的浏览器,因此您可能希望在 javascript 框架中使用类似的方法。 Jquery 允许使用选择器通过类名获取元素

$('.nums')

【讨论】:

  • 在这里查看一个跨浏览器的实现 - robertnyman.com/2008/05/27/…
  • 应该在上面说浏览器,我似乎受到打字口齿不清的影响:)
  • .getElementByClassName 不幸的是在 IE8 中不起作用(没有解决方法),我会说这是一个相当新的浏览器。
猜你喜欢
  • 2019-06-22
  • 1970-01-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
相关资源
最近更新 更多