将两个动态生成的HTML值与jQuery一起添加

时间:2015-05-23 11:36:07

标签: jquery

我正在创建一个定价界面,最终会为用户产生两种不同的价格(体验+收藏)。然后我需要结合这些价格才能显示总价。根据用户的选择显示体验和收集价格,它们目前效果很好。

但现在我无法弄清楚如何添加两个html元素的html值。类total-cost是应显示此附加值的位置。我已经尝试过很多东西,希望自己搞清楚,但没有运气。

谢谢!

HTML(已清理)

<div class="pricing-experience">

    <div class="flex_column">
        <span class="cost1">3000</span>
    </div>

    <div class="flex_column">
        <span class="cost1">4000</span>
    </div>

    <div class="flex_column">
        <span class="cost1">5000</span>
    </div>

</div>


<div class="pricing-collection">

    <div class="flex_column">
        <span class="cost2">300</span>
    </div>

    <div class="flex_column">
        <span class="cost2">450</span>
    </div>

    <div class="flex_column">
        <span class="cost2">700</span>
    </div>

</div>


<div class="experience-cost">
//cost1's value
</div>

<div class="collection-cost">
//cost2's value
</div>

<div class="total-cost">
//cost1 and cost2's added value
</div> 

的jQuery

$('.pricing-experience, .pricing-collection').on('click', '.flex_column', function() {

    var experienceCost = $(this).find('.cost1').html(),
        collectionCost = $(this).find('.cost2').html();

    $(this).addClass('elephant').siblings().removeClass('elephant');

    // console.log(experienceCost);
    // console.log(collectionCost);

    $('.experience-cost').html(experienceCost);

    $('.collection-cost').html(collectionCost);

    $('.total-cost').html(experienceCost + collectionCost);

});

2 个答案:

答案 0 :(得分:0)

试试这个:

为每个div .cost1.cost2在变量中添加值,然后在div中显示

JS:

$(".btn1").click(function () {

var experienceCost = 0;
var collectionCost = 0;
var totalCost = 0;
$('.cost1').each(function () {
    experienceCost += parseFloat($(this).text());
});
$('.cost2').each(function () {
    collectionCost += parseFloat($(this).text());
});

$('.experience-cost').text(experienceCost);
$('.collection-cost').text(collectionCost);
$('.total-cost').text(experienceCost + collectionCost);
});

HTML:

<div class="pricing-experience">
<div class="flex_column"> <span class="cost1">3000</span>

</div>
<div class="flex_column"> <span class="cost1">4000</span>

</div>
<div class="flex_column"> <span class="cost1">5000</span>

</div>
</div>
<div class="pricing-collection">
<div class="flex_column"> <span class="cost2">300</span>

</div>
<div class="flex_column"> <span class="cost2">450</span>

</div>
<div class="flex_column"> <span class="cost2">700</span>

</div>
</div>
<div class="experience-cost"></div>
<div class="collection-cost"></div>
<div class="total-cost"></div>
<button class="btn1">experienceCost</button>

Working Fiddle

答案 1 :(得分:0)

您需要在点击时找到匹配的值:

var k=0, e=this;
while (e = e.previousElementSibling) { ++k;}

这是一个粗略的演示:http://jsfiddle.net/y3Ls4zso/1/

如果我明白你想做什么......

相关问题