如何通过JavaScript闭包将表单数值以数字类型传递给其他函数?
解决闭包获取表单金额数值的问题
问题根源
- 初始化时
const transaction_amount = get_transaction_amount();无参数调用,此时amount为undefined,parseInt(undefined,10)返回NaN,这个包含NaN的闭包被赋值给了transaction_amount。 - 点击按钮时调用
get_transaction_amount(document.getElementById('amount').value),虽然生成了包含正确金额的新闭包,但这个闭包没有被保存到transaction_amount变量中,后续make_me_a_number调用的还是初始的闭包,自然返回NaN。
修改方案
方案一:点击按钮时更新闭包引用
修改按钮的点击事件,将返回的新闭包赋值给transaction_amount,并触发数值获取逻辑:
HTML代码修改:
<p> 您想要购买多少? <input type="number" maxlength="3" name="purchase_amount" id="amount" /> <input type="button" value="提交" onclick="transaction_amount = get_transaction_amount(document.getElementById('amount').value); make_me_a_number();" /> </p>
JS代码修改:
function get_transaction_amount(amount) { let cost = parseInt(amount, 10) console.log(cost); console.log(`the type of costs is ${typeof(cost)}`) return function pass_transaction_amount() { console.log(`This is the result = ${cost}`); console.log(`From the return function cost is a ${typeof(cost)}`); return cost } } // 用let声明变量,允许后续重新赋值闭包 let transaction_amount = get_transaction_amount(); function make_me_a_number() { const value = transaction_amount() console.log(value); }
方案二:让闭包动态获取最新表单值
调整函数逻辑,让闭包直接绑定输入框元素,每次调用时自动读取最新输入值:
JS代码修改:
function get_transaction_amount() { // 保存输入框元素到闭包中 const amountInput = document.getElementById('amount'); return function pass_transaction_amount() { let cost = parseInt(amountInput.value, 10); console.log(cost); console.log(`the type of costs is ${typeof(cost)}`); console.log(`This is the result = ${cost}`); console.log(`From the return function cost is a ${typeof(cost)}`); return cost; } } // 仅初始化一次闭包 const transaction_amount = get_transaction_amount(); function make_me_a_number() { const value = transaction_amount() console.log(value); }
HTML代码简化:
<p> 您想要购买多少? <input type="number" maxlength="3" name="purchase_amount" id="amount" /> <input type="button" value="提交" onclick="make_me_a_number();" /> </p>
内容的提问来源于stack exchange,提问作者simplytrue
相关产品推荐
相关产品推荐

