无法对每个元素应用函数

时间:2015-07-15 18:24:06

标签: jquery each

我无法使用以下代码向页面上的每个#sum应用函数:

$(document).ready(function() {


    $('#sum').each(function(index, element) {
        var sum = $(this).html();
        $(element).html(number_format(sum, 2, ',', ' '));

        console.log(element);
    });


});



function number_format(f,c,h,e){f=(f+"").replace(/[^0-9+\-Ee.]/g,"");var b=!isFinite(+f)?0:+f,a=!isFinite(+c)?0:Math.abs(c),j=(typeof e==="undefined")?",":e,d=(typeof h==="undefined")?".":h,i="",g=function(o,m){var l=Math.pow(10,m);return""+Math.round(o*l)/l};i=(a?g(b,a):""+Math.round(b)).split(".");if(i[0].length>3){i[0]=i[0].replace(/\B(?=(?:\d{3})+(?!\d))/g,j)}if((i[1]||"").length<a){i[1]=i[1]||"";i[1]+=new Array(a-i[1].length+1).join("0")}return i.join(d)};

它仅适用于第一个元素。 DEMO

2 个答案:

答案 0 :(得分:1)

您正在使用id选择器。将其更新为class选择器

标记

First: <span class="sum">4326544</span><br>
Second: <span class="sum">654654</span><br>
Last: <span class="sum">43264</span>

JS

$('.sum').each(function(index, element) {

更新了小提琴 - http://jsfiddle.net/mwcnz2k2/1/

答案 1 :(得分:1)

不要在多个元素上使用相同的ID。而是使用类

&#13;
&#13;
$(document).ready(function() {


  $('.sum').each(function(index, element) {
    var sum = $(this).html();
    $(element).html(number_format(sum, 2, ',', ' '));

    console.log(element);
  });


});



function number_format(f, c, h, e) {
  f = (f + "").replace(/[^0-9+\-Ee.]/g, "");
  var b = !isFinite(+f) ? 0 : +f,
    a = !isFinite(+c) ? 0 : Math.abs(c),
    j = (typeof e === "undefined") ? "," : e,
    d = (typeof h === "undefined") ? "." : h,
    i = "",
    g = function(o, m) {
      var l = Math.pow(10, m);
      return "" + Math.round(o * l) / l
    };
  i = (a ? g(b, a) : "" + Math.round(b)).split(".");
  if (i[0].length > 3) {
    i[0] = i[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, j)
  }
  if ((i[1] || "").length < a) {
    i[1] = i[1] || "";
    i[1] += new Array(a - i[1].length + 1).join("0")
  }
  return i.join(d)
};
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
First: <span class="sum">4326544</span>
<br>Second: <span class="sum">654654</span>
<br>Last: <span class="sum">43264</span>
&#13;
&#13;
&#13;

请参阅Why is it a bad thing to have multiple HTML elements with the same id attribute?