首页 > 解决方案 > 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() {}

标签: javascripthtmldom-eventscalculator

解决方案


试试这个方法。

// 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() {}


推荐阅读