jQuery to loop through dynamically created elements with the same class

I have no. of div which is created dynamically in button click.

<table>
   <tbody id="ProductDetail"></tbody>
</table>

In button click, some no. of div are created with Amount value.

funtion createDiv(){
  $("#ProductDetail").append("<tr><td ><div class='Amount'>"+Amount+"</div></td></tr>");
}

I want to loop through these dynamically created div to get Amount values in jquery.I tried below code. But its not iterating loop.

function calculateAmount(){
    $('.Amount').each(function (i, obj) {
         TotalAmountValue=TotalAmountValue+$(this).html();
    });
}

Please anybody help me.


I got this working just fine!

$(document).ready(function(){
          $("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
          $("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");
          $("#ProductDetail").append("<tr><td><div class='Amount'>3</div></td></tr>");

          $("#sum").click(function()
          {
              var sum = 0;
              $(".Amount").each(function()
              {
                  sum += parseInt($(this).text());
              });
              alert(sum);
          });
      });

the .each iterates through all your elements that have the class Amount . Use the . selector for class and add the name. Index represents the position, while the val is the current element.

Edit: get a local variable and set it to 0. After that, iterate through all the elements with that class and take their text. Since it is String , js will try to convert the sum variable to String . You need to parse the text to int . This is a working example.

Here is the HTML

  <table>
      <tbody id="ProductDetail"></tbody>
  </table>
  <input type="button" id="sum" value="Sum">

尝试使用text()

$('.Amount').each(function (i, obj) {
  TotalAmountValue += parseInt($(this).text());
});

 $('.Amount').each(function(index, val)
    {
        //do something
    }); 
链接地址: http://www.djcxy.com/p/83514.html

上一篇: jQuery通过具有类后缀的元素循环

下一篇: jQuery使用相同的类来动态创建元素