jQuery:数字未更新,更改为0

jQuery: Number not updating, changing to 0

本文关键字:更新 数字 jQuery      更新时间:2023-09-26

我正在尝试使用jQuery计算物品的税款。我使用的CRM有一种叫做标签的东西,它采用{tag_something}的形式来动态读取网页上的信息。我想使用jQuery更新产品的价格。(稍后将针对州具体税收实施)。我的代码正在更改原始价格,但没有将其更改为需要的价格,而是在页面上默认为"0"。任何想法或建议都将不胜感激。我为此设置的产品是:http://www.bemidjisportsonline.com/accessories/backpacks/klim-nac-pak

<!-- taxable items -->
jQuery(document).ready(function() {
    initUpdateTax();
}   
);
function initUpdateTax() {
var taxable = '{tag_taxcode}';
var saleprice = '{tag_saleprice}';
if  (taxable == "Accessories"){
    $('#taxable').text(function(saleprice) {
        return Math.round(parseInt(saleprice + (saleprice * 0.06875));  
    });
}
}

在文本框的change事件中再次调用该方法。。

$('.productTextInput').on('change', function() {
     initUpdateTax();
});

您似乎只是在第一次加载页面时才调用该方法。每当输入框更改时,您需要再次调用它。。

更好

jQuery(document).ready(function () {
    // Change event
    $('.productTextInput').on('change', initUpdateTax)
        .change(); // Trigger the change on DOM ready
});
function initUpdateTax() {
    var saleprice = '{tag_saleprice}';
    // Find the corresponding element wherein the 
    // total price has to be shown
    var $total = $(this).closest('li')
        .prevAll('.price').first().find('strong');
    $total.text(function (saleprice) {
        return Math.round(parseInt(saleprice + (saleprice * 0.06875)));
    });
}

在您发布的链接之后,正在执行的代码是:

function initUpdateTax() {
    var taxable = 'Accessories';
    var saleprice = '$95.99';
    if  (taxable == "Accessories"){
        $('#taxable').text(function(saleprice) {
            return Math.round(parseInt(saleprice + (saleprice * 0.06875));  
        });
    }
    else {
    }
}

salesprice的值不是有效的数字,因此乘以saleprice * 0.06875得到NaNreturn表达式的行中也缺少一个括号。

此外,使用parseIntMath.round运算没有多大意义,因为第一个运算的返回值是一个整数,当四舍五入时它本身就是整数。对价值征税可以用以下更简洁(且IMHO清晰)的方式saleprice * 1.06875表示。

这是功能的一个版本,可以实现您的期望:

function initUpdateTax() {
    var taxable = '{tag_taxcode}';
    if  (taxable == "Accessories"){
       var saleprice = $('#taxable').text();
       var price = parseFloat(saleprice.replace('$', '')) * 1.06875;
       $('#taxable').text('$' + price.toFixed(2));
    }
    else {
    }
}