0

When I click a div, I'm trying to grab data from previous divs with the same class. My HTML would look something like this.

<div class="theDiv one">
   <div class="info"> Lorem </div>
   <div class="theNumber"> 2 </div>
</div>
<div class="theDiv two">
   <div class="info"> Lorem </div>
   <div class="theNumber"> 4 </div>
</div>
<div class="theDiv three">
   <div class="info"> Lorem </div>
   <div class="theNumber"> 3 </div>
</div>
<div class="theDiv four">
   <div class="info"> Lorem </div>
   <div class="theNumber"> 1 </div>
</div>

If I were to click any div with the class 'theDiv', I'd like to grab the numbers inside the previous divs that also have the class 'theDiv", and add them up. For example, if I clicked the third div, my sum would be 6.

I'm at a loss at how to do this elegantly, instead of just traversing the heck out of it, with an if statement for each div.

4

2 回答 2

2

Try:

$(document).ready(function(){
    $(".theDiv").click(function(){
        var sum = 0;
        $(this).prevAll(".theDiv").find(".theNumber").each(function(){
            sum += parseInt($(this).text(), 10);
        });
                    alert(sum);
    });
});

DEMO FIDDLE

于 2013-09-06T05:29:04.347 回答
1

给你:(演示

$(".theDiv").click(function () {
    var sum = eval($(this).prevAll()
        .find(".theNumber").text().split("").join("+") || 0);

    alert(sum);
})
于 2013-09-06T05:30:06.820 回答