簡體   English   中英

為什么我得到NaN值?

[英]Why am I getting an NaN value?

我的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');
        }
    }
});

服務器返回的JSON數據是:

{ “價格”: “52.00”}

這里, this是指文本框。 我得到了表達式的NaN值:

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

但我確保this.valuejson.price都是數字。 那么,為什么當我乘以NaN時會得到NaN?

問題是this不在post函數的范圍內。

檢查下面的代碼。 我添加了一個新的變量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');
        }
    }
});

您可以使用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