开发者

navigating the dom

what's the best way to show each blocks' respective sum in the labels provided ?

  <div class='block1'><label for='blockSum'>Sum goes here</label>
    <div class='head'>
      <div class='title'>
        <开发者_C百科div class='sumMe'>$1.01</div>
      </div>
    </div>          
    <div class='head'>
      <div class='title'>
        <div class='sumMe'>$2.01</div>
      </div>
    </div>
  </div>
  <div class='block2'><label for='blockSum'>Sum goes here</label>
    <div class='head'>
      <div class='title'>
        <div class='sumMe'>$1.01</div>
      </div>
    </div>          
    <div class='head'>
      <div class='title'>
        <div class='sumMe'>$2.01</div>
      </div>
    </div>
  </div>


Assuming each block as a class block:

$('.block').each(function() {
    var total = 0; // total in cents
    $(this).find('.sumMe').each(function() {
        var parts = $(this).text().replace('$', '').split('.'); // prepare text
        total += +parts[0] * 100 + (+parts[1] || 0); // compute value in cents
    });
    $(this).find('label').text('$' + (total/100).toFixed(2)); // write sum
});

DEMO

Don't use float values for computations with money (though there might be easier ways than mine).


Try this

$('.block1,.block2').each(function(){
     var total=0;
     $('.sumMe',this).each(function(){
         total = total + parseFloat($(this).text().replace('$',''));
     });

     $(this).find("label").html("$"+total);
});


Something like this should do the trick, although using parseFloat will result in silly values for money:

$('div[class^="block"]').each(function() {
    var total = 0;
    $(this).find(".sumMe").each(function() {
       total += parseFloat($(this).text().replace("$", ""));
    });
    $(this).find("label").text("TOTAL: " + total);
});

This finds all div elements with class beginning with "block" (note that the block class would have to be the first class listed if you have multiple classes), loops through the matched set, converts the required strings to floats, adds up each one as it goes, and writes the result to the label element.


$('.block1,.block2').each(function(){
     var sumValue=0;
     $('.sumMe',this).each(function(i,v){
         sumValue=sumValue+parseFloat($(v).text().replace('$','')||0);
     });
     $('label:first',this).html('$'+sumvalue);
});


This should do it

$('div[class^="block"]').each(function() {
    var sum = 0; //create a sum variable for each block
    var block = $(this);
    block
        .find('.sumMe') // find the .sumMe elements for each block
        .each(function() {
           sum += +$(this).text().replace('$', ''); // convert text to number and add to sum 
        })
        .end() // return to block element
        .prepend('Sum of ' + block.attr('class') + ' is ' + Math.round(sum*100)/100); // prepend the sum to the block

});

demo at http://jsfiddle.net/gaby/r2yq9/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜