javascript - JS 事件问题 - 存储提示值并稍后调用它们
问题描述
试图为自己构建一个计算器,它需要两个提示数字,然后有一组单独的按钮来评估它们
我遇到的问题如下,我将提示的 number1 和 number2 保存为变量,但是当我尝试在外部函数中调用变量时,它告诉我变量(number1 和 number2)没有定义
有什么帮助吗?
ps:我已经开始做添加按钮了,然后会添加sub/mult/div,只需要让第一个去
// the user is required to choose two sets of numbers that are then stored as variables
function numRequest() {
var number1 = prompt('choose the first number to evaluate:');
var number2 = prompt('choose the second number to evaluate:');
// just an external checker to see if the prompt is being saved
console.log('first choice --> ' + number1);
console.log('second choice --> ' + number2);
// the numbers, stored as variables, are displayed on the calculator window
document.getElementById('resBanner').innerHTML = ('you chose ' + number1 + ' and ' + number2);
}
// this is where the problem arises
// when i press the button that summons the function addition(), the two numbers arent
// defined for some reason
function addition() {
var res = Number(number1) + Number(number2);
document.getElementById('resBanner').innerHTML = res;
}
// function subtraction() {}
// function division() {}
// function multiplication() {}
解决方案
试试这个方法。
// the user is required to choose two sets of numbers that are then stored as variables
let number1;
let number2;
function numRequest() {
number1 = prompt('choose the first number to evaluate:');
number2 = prompt('choose the second number to evaluate:');
// just an external checker to see if the prompt is being saved
console.log('first choice --> ' + number1);
console.log('second choice --> ' + number2);
// the numbers, stored as variables, are displayed on the calculator window
document.getElementById('resBanner').innerHTML = ('you chose ' + number1 + ' and ' + number2);
}
// this is where the problem arises
// when i press the button that summons the function addition(), the two numbers arent
// defined for some reason
function addition() {
var res = Number(number1) + Number(number2);
document.getElementById('resBanner').innerHTML = res;
}
// function subtraction() {}
// function division() {}
// function multiplication() {}
推荐阅读
- jquery - jQuery .find('li').length 必须来自兄弟/孩子?
- java - 尝试构建 Rest 服务时 Spring Boot 失败
- r - 根据第二个数据帧 R 上的索引替换数据帧中的值
- vba - 如何将记录信息从 ListBox 存储到 Table?
- java - 一旦我在函数之外,优先队列中的值就会被删除,为什么?
- android - 如何使用 popBackStack() 返回到我的 Android 应用程序中的上一个片段?
- python - 密码包含特殊字符时“拒绝用户访问”
- mysql - MySQL 合并 2 个结果集,不包括第一个中的记录
- php - PHP 是否具有确定与给定 PHP 脚本兼容的最旧 PHP 版本的内置方法?或者永远不会?
- c# - 如何让 WPF 应用程序打开另一个应用程序(如果存在)