.each函数中带逗号的格式编号

时间:2016-03-21 20:09:05

标签: javascript jquery html

所以我有一些js通过每日汇率引擎转换div类的数字。它正确地输出它应该和我现在尝试使用jQuery和我在进行一些研究时发现的函数来分离它输出的数字。我正在尝试使用.innerHTML方法将数字提供给函数。我有一个函数来提醒转换后的数字,但是我有多个这个函数应该运行的元素,所以使用了.each函数 - 这是某些东西不起作用的地方。我没有得到警告,所以我认为.each代码有问题。

任何人都可以看到可能导致它的任何事情吗?

完整的代码在这里:

<script src="https://raw.githubusercontent.com/openexchangerates/money.js/master/money.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>


<div class="hello">
  2300
</div>

<div class="hello">
  52400
</div>




<script>

    function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var n= yourNumber.toString().split(".");
    //Comma-fies the first part
    n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //Combines the two sections
    return n.join(".");
}

    $(".hello").each(function() {

    var currentDiv = $(this);
    var currentPrice = currentDiv.text();

    var demo = function(data) {
    fx.rates = data.rates
    var rate = fx(currentPrice).from("GBP").to("USD");
    currentDiv.html("<div>"+currentPrice +"</div><div id='converted'> " +rate.toFixed(0)+"</div>");
        //alert("Product Costs" + rate.toFixed(4))

}
    $.getJSON("http://api.fixer.io/latest", demo);
});


    $("#converted").each(function() {
        var convertedPrice = $(this.innerHTML);
        function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) }
        setTimeout (runThis, 100);
    });

</script> 

1 个答案:

答案 0 :(得分:0)

我认为原因是

$("#converted").each(function() { var convertedPrice = $(this.innerHTML); function runThis() { alert( ReplaceNumberWithCommas(convertedPrice)) } setTimeout (runThis, 100); });

在创建转换后的元素之前发生。因为你把创作放在了一个get call中。

我建议你把它放在你来电的回调中。

像这样的东西

  function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var n = yourNumber.toString().split(".");
    //Comma-fies the first part
    n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    //Combines the two sections
    return n.join(".");
  }
    var currentDiv = $(this);
    var currentPrice = currentDiv.text();

    var demo = function(data) {
      fx.rates = data.rates
      $(".hello").each(function() {
        var currentDiv = $(this);
        var currentPrice = currentDiv.text();
        var rate = fx(currentPrice).from("GBP").to("USD");
        currentDiv.html("<div>" + currentPrice + "</div><div class='converted'> " + rate.toFixed(0) + "</div>");
        //alert("Product Costs" + rate.toFixed(4))
      });

      $(".converted").each(function() {
        var convertedPrice = $(this).html();
        console.log(ReplaceNumberWithCommas(convertedPrice));
      });
    }    
  $.getJSON("https://api.fixer.io/latest", demo);