使用jquery更改's中的值

时间:2012-11-15 08:23:23

标签: javascript jquery

我有一张价值表。通过单击货币链接来更改单元格中的汇率是否可以使用JQuery?这个静态示例表

<table border="1">
    <tr>
      <td class="currency">100</td>
      <td class="currency">200</td>
      <td class="current">now in USD</td>
    </tr>
    <tr>
      <td class="currency">150</td>
      <td class="currency">230</td>
    </tr>
    <tr>
      <td class="currency">400</td>
      <td class="currency">200</td>
    </tr>
    <tr>
      <td class="currency">550</td>
      <td class="currency">2920</td>
    </tr>
  </table>

  <a href="#" class="USD">USD</a>
  <a href="#" class="EUR">EUR</a>

请看jsfiddle。换句话说,点击货币值必须根据费率重新计算。在我关于jsfiddle的示例中,我想了解如何简单地更改值(例如usd=1 eur=1.3)谢谢!

3 个答案:

答案 0 :(得分:4)

首先,您需要存储原始美元价值,以便将其作为所有汇率的基础。 data-x属性非常适用于此。

$('.currency').each(function() {
    $(this).data('usd-value', $(this).text());
});

然后,您可以简单地将此值乘以您需要的任何汇率,再次存储在链接本身的data属性中。试试这个:

<a href="#" class="exchange USD" data-exchangerate="1">USD</a>
<a href="#" class="exchange EUR" data-exchangerate="1.3">EUR</a>
<a href="#" class="exchange GBP" data-exchangerate="0.63">GBP</a>
$(".exchange").click(function() {
    var rate = $(this).data('exchangerate');
    $('.currency').each(function() {
        $(this).text(parseFloat($(this).data('usd-value') * rate));
    });
});

Example fiddle

注意我还添加了GBP只是为了展示这种方法的可扩展性。

答案 1 :(得分:1)

你也可以这样做: -

var flag = false;
$('.USD').click(function() {
    if (flag)
    {
        $('.currency').each(function() {
            $(this).text(parseFloat($(this).text() / 1.3));
        });
        flag = false;
        $('.current').text("Now in USD");
        $('.EUR').removeAttr("disabled");
    }
});
$('.EUR').click(function() {
    flag = true;
    $('.currency').each(function() {
        $(this).text(parseFloat($(this).text() * 1.3));
    });
    $('.current').text("Now in EUR");
    $(this).attr("disabled", "disabled");
});

参考 LIVE DEMO

答案 2 :(得分:0)

您可以按类选择它们并进行修改:

$('.currency').each(function(){
    var eurMultiplier = 1.3;
    var currentValue = parseInt($(this).html());
    var newValue = currentValue * eurMultiplier;
    $(this).html(newValue);
});

此代码未经测试,但请提示您如何操作。