简体   繁体   English

为什么我得到NaN值?

[英]Why am I getting an NaN value?

My jQuery is: 我的jQuery是:

$("#listDB").on("change", ".qfStyle", function(event) {
    var id = $(this).parents("tr").find('.itemCbox').val();
    $qnty = $("#qnty"+id);
    $unit = $("#unit"+id);
    $price = $("#price"+id);

    if($(this).parents("tr").find('.pbo').text()=="Kilos")
    {
        if(this.value<1)
        {
            $qnty.text(this.value*1000);
            $unit.text("gm");

            var data = "action=getPrice&id="+id;
            $.post("addBill.php", data, function(json) {
                alert(json.price);
                $price.text(json.price*this.value);
            }, 'json');
        }
    }
});

The JSON data returned by the server is: 服务器返回的JSON数据是:

{"price":"52.00"} { “价格”: “52.00”}

Here, this refers to a textbox. 这里, this是指文本框。 I'm getting the value NaN for the expression: 我得到了表达式的NaN值:

$price.text(json.price*this.value);

But I've ensured that both this.value and json.price are both numbers. 但我确保this.valuejson.price都是数字。 So, why do I get NaN when I multiply them? 那么,为什么当我乘以NaN时会得到NaN?

The problem is that this isn't in a scope of a post function. 问题是this不在post函数的范围内。

Check the code below. 检查下面的代码。 I added a new variable value which holds the value of this.value and which should be available even in a post function. 我添加了一个新的变量value ,它保存this.value的值,即使在post函数中也应该可用。

$("#listDB").on("change", ".qfStyle", function(event) {
    var id = $(this).parents("tr").find('.itemCbox').val();
    $qnty = $("#qnty"+id);
    $unit = $("#unit"+id);
    $price = $("#price"+id);

    var value = this.value;

    if($(this).parents("tr").find('.pbo').text()=="Kilos")
    {
        if(value<1)
        {
            $qnty.text(value*1000);
            $unit.text("gm");

            var data = "action=getPrice&id="+id;
            $.post("addBill.php", data, function(json) {
                alert(json.price);
                $price.text(json.price*value);
            }, 'json');
        }
    }
});

You can use Number() to extract a string number to number format. 您可以使用Number()将字符串编号提取为数字格式。

 function getStringNumber(stringNumber){ var formatNumber = Number(stringNumber); console.log(formatNumber); } 
 <html> <button onclick="getStringNumber('24.00')"> Convert String Number </button> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM