onclick单选按钮将数字加到总数中,但无限地加

时间:2019-06-17 13:31:30

标签: javascript php jquery wordpress

我有这个jQuery代码

var theTotal = jQuery('.woocommerce-Price-amount.amount').text();
var price = theTotal.replace("$", "");

jQuery('input[name="dimming"]').bind('click', function (e) {
    var haller = jQuery(this).val();

    if (haller == '1-10V dimmer') {
        price = Number(price) + 150;
    } else {
        price = Number(price) - 150;
    }

    jQuery('.woocommerce-Price-amount.amount').text(price); 

});

我有这个单选按钮,所以当我选择单选按钮“ layer2”时,它应该在原始金额上增加150

[] layer1 (+ $0)
[] layer2 (+ $150)

结果

<span class="woocommerce-Price-amount amount">746</span>

但是当我多次单击layer2时,它总是累加起来,无论我选择了多少次该按钮,它应该始终是原始价格+ 150,

这里是我的https://jsfiddle.net/kxvc6t2L/

2 个答案:

答案 0 :(得分:3)

您可以将原始Price保存到变量中,然后只需要在layer1 150上添加价格。因此,您将始终从原始价格150中添加价格。这样,您将不会更改该价格,也无法获得更多。

var theTotal = jQuery('.woocommerce-Price-amount.amount').text();
var originalPrice = theTotal.replace("$", "");

jQuery('input[name="dimming"]').bind('click', function (e) {
    var haller = jQuery(this).val();

    if (haller == '1-10V dimmer') {
        price = Number(originalPrice) + 150;
    } else {
        price = Number(originalPrice);
    }

    jQuery('.woocommerce-Price-amount.amount').text(price); 

});

这是您的工作小提琴: https://jsfiddle.net/bno4qsuk/

答案 1 :(得分:0)

此如何:https://jsfiddle.net/wwWaldi/k4wfyg3L/3/

var theTotal = jQuery('.woocommerce-Price-amount.amount').text();
var price = Number(theTotal.replace("$", ""));

jQuery('input[name="dimming"]').bind('click', function (e) {
    var haller = jQuery(this).val();

    if (haller == '1-10V dimmer') {
        price += 150;
    } else {
        price -= 150;
    }

    jQuery('.woocommerce-Price-amount.amount').text(price); 

});
相关问题