不是每次NaN显示时都在jquery中进行乘法运算

Not work multiplication in jquery every time NaN show

本文关键字:jquery 运算 NaN 显示      更新时间:2023-09-26

我从span标记和文本框中获取值,并将它们相乘,但它不能正常工作。当我检查浏览器时,我会播种来自span标记和文字框的值,但相乘值(totalprice)显示NaN。

 $("#addintocart").click(function () {
        debugger;
        var productid = $("#product_id").text();
        var cartid = $("#userid").text();
        var quentity = $("#txt_quentity").val();
        var price = $("#p_price").text();
        var totalprice =(quentity * price);
        $.ajax({
            url: '/Product/AddInCart',
            type: 'GET',
            data: { cartid: cartid, productid: productid, quentity: quentity, totalprice: totalprice },
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                //your success code
                // also count total 
                alert("Success");
               // Successnotify();
                });
            },
            error: function () {
                alert("some error");
            }
        });
    })

你能检查吗

var totalprice =(Number(quentity) * Number(price));

您将price作为$.text()的字符串。当您在javascript中将数字与字符串相乘时,您将获得值NaN。尝试使用Number()函数强制转换您的值。

将它们解析为数字。

  1. var totalprice = parseInt(quentity) * parsefloat(price);
  2. var totalprice = (~~quentity) * parseFloat(price);

您正在返回字符串,需要将它们转换为数字。

如果您有标准的数字输入,那么parseFloatNumber之间没有区别。当您的输入以数字开头并包含其他字符时,parseFloat会截断字符串中的数字,而number返回NaN(不是数字):

parseFloat('23x'); // => 23
Number('23x'); // => NaN

Number也理解类似23e5(即2300000)的符号

另一件事是你可以使用+,它的行为就像Number

var totalprice = (Number(quentity) * Number(price));
var totalprice = (+quentity) * (+price);

请注意,两者都将"023"转换为八进制,即19位数字(十进制)

请注意,不清楚您的quentity是否是数量,如果是,数量通常是一个整数,因此您可能会将parseInt视为该数字