首页 > 解决方案 > jQuery:单击时更改 div 文本,不会多次使用

问题描述

这是我的代码:

    var woocommerce_price_displayed = $('.product_intial_price').find('.woocommerce-Price-amount').text();

        $(".yearly-package").click(function () {
        var yearprice = $('#year_price').text();
    $('.electro-price').find('.woocommerce-Price-amount').text(function () {
    return $(this).text().replace(woocommerce_price_displayed, yearprice); 
});
    })

    $(".halfyear-package").click(function () {
       var halfyearprice = $('#halfyear_price').text();
$('.electro-price').find('.woocommerce-Price-amount').text(function () {
    return $(this).text().replace(woocommerce_price_displayed, halfyearprice); 
});
    })

    $(".single-package").click(function () {
      var oneprice = $('#one_price').text();
$('.electro-price').find('.woocommerce-Price-amount').text(function () {
    return $(this).text().replace(woocommerce_price_displayed, oneprice); 
});
    })


单击 div 时,价格会发生变化。但是,如果我再次点击不同的按钮 - 价格不会再次改变。

怎么了?为什么它只在第一次点击时起作用?

这基本上是每个包的 html:

<div class="ps-package single-package first-pack" data-val="1">
<div class="ps-name">Single Package</div>
<div id="one_price" class="ps-price">$99</div>

</div>

<span class="electro-price"><ins><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>99.00</span></ins> <del><span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">$</span>150.00</span></del></span>

当我var woocommerce_price_displayed = oneprice;像这样为每个函数添加时:

    $(".halfyear-package").click(function () {
       var halfyearprice = $('#halfyear_price').text();
$('.electro-price').find('.woocommerce-Price-amount').text(function () {
    return $(this).text().replace(woocommerce_price_displayed, halfyearprice); 
    woocommerce_price_displayed = halfyearprice;
});

它根本行不通,甚至一次都行不通!为什么?

标签: javascriptjquery

解决方案


推荐阅读