0

我在 php/mysql 中有一个动态表,我通过复选框显示/隐藏列。下面的代码片段是隐藏和重新计算总列的单元格值的 javascript 的一部分。

function toggleVis(button) { 
// Toggle column 
cells = $$('.t'+button.name); 
cells.invoke(button.checked ? 'show' : 'hide'); 

// Recaulculate total 
$$('tr.row').each(function(row) { 
// Initialise to zero 
var total = 0; 
row.down('.total').textContent = total; 

// Sum all visible cells 
row.select('td').each(function(cell) { 
total += cell.visible() ? parseInt(cell.textContent, 10) : 0;
}); 

// Write the total in the total cell 
row.down('.total').textContent = total; 
}); 
}

当表格内容只是数字时,这很有效,但我现在需要创建另一个包含货币值的表格。这可能导致总列返回NaN可能是由于 £ 符号。我使用以下代码在 php 中对其进行格式化:

     <tbody>
  <?php do { ?>
    <tr>
      <td><?php echo $row_rsMISource['Source']; ?></td>
      <td><?php echo "£".number_format($row_rsMISource['May'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Jun'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Jul'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Aug'], 2, '.', ','); ?></td>
      <td><?php echo "£".number_format($row_rsMISource['Total'], 2, '.', ','); ?></td>
      </tr>
    <?php } while ($row_rsMISource = mysql_fetch_assoc($rsMISource)); ?>
    </tbody>

这会输出诸如 £10,169.62、£7,053.00 或 £.0.00 之类的值

在仍然使用上面发布的 js 的同时,是否可以用货币格式化单元格?

4

1 回答 1

5
4 + '£4'; //NaN
4 + parseFloat('£4.3'.replace(/[^\d\.]/g, '')); //8.3

这会从字符串中删除非数字字符,并将字符串强制转换为数字(所以你得到8.3,而不是"44.3")。

如果您居住的国家/地区使用逗号而不是句点作为小数分隔符,请替换\.,

[编辑-对于您的具体示例:]

row.find('td').each(function() { 
    total += $(this).is(':visible') ? parseFloat($(this).text().replace(/[^\d\.]/g, '')) : 0;
});

那里有很多代码更改。

于 2012-07-30T11:44:37.757 回答