繁体   English   中英

为什么我的javascript函数仅在我手动输入时才起作用?

[英]Why does my javascript function only work if I manually type in the inputs?

当手动设置值时,我有一个可以完美工作的函数

function doSomeMath(array,number){
  some math here.....
}

仅当我手动设置每月帐单时才有效

function customer(){
 this.monthlyBill = 300;
}

当我这样做时,它可以正常工作:

var someArray = [.2,.3,.6];
var customerData = new customer();
doSomeMath(someArray,customerData.monthlyBill);

问题是我不想手动设置它,我想从表单输入元素获取值。

当我这样做时,它搞砸了:

function customer(){
 this.monthlyBill = $('#monthly_bill').val(); 
}

我进入#monthly_bill表格并输入300,我得到一个完全不同的值。

我打字有什么区别

this.monthlyBill = 300

this.monthlyBill = $('#monthl_bill').val();    // and then typing 300 into a form.

在第二种情况下

this.monthlyBill = $('#monthl_bill').val(); 

它被认为是字符串。 您需要将其解析为整数

所以基本上:

this.monthlyBill = parseInt($('#monthl_bill').val()); 

发表我的评论和演示

300是一个数字-xxx.val()是一个字符串-尝试parseInt($('#monthl_bill')。val(),10);

,如果有人输入前导0,则需要10个基数,因为这表示八进制

演示

暂无
暂无

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

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