2 回答
TA贡献1831条经验 获得超4个赞
在这里你可以看到用全局变量解决了你的问题。
var value1, value2;
function add() {
value1 = parseInt(document.getElementById("value1").value);
value2 = parseInt(document.getElementById("value2").value);
if(value1 && value2){
added = value1 + value2;
document.getElementById("output").innerHTML = added;
checkGlobalVal();
}else{
console.log('Please give the input value.');
}
}
function checkGlobalVal(){
console.log('value1:',value1,' value2:',value2);
}
First no:<input type="number" id="value1"><br> Second no:<input type="nunmber" id="value2"><br>
<button onclick="add()">add</button><br> output: <span id="output"></span>
TA贡献1810条经验 获得超4个赞
您可以将变量赋值移动到函数内部,这样每次设置函数时它们都会被设置,因此您不必从HTML端传递它们:
function add() {
var value1 = parseInt(document.getElementById("value1").value);
var value2 = parseInt(document.getElementById("value2").value);
var added = value1 + value2;
document.getElementById("output").innerHTML = added;
}
First no:<input type="number" id="value1"><br> Second no:<input type="nunmber" id="value2"><br>
<button onclick="add()">add</button><br> output: <span id="output"></span>
编辑:如果您希望变量是全局变量,您可以使用事件侦听器:
var value1, value2;
document.getElementById("value1").addEventListener('input', function (evt) {
value1 = +evt.target.value
});
document.getElementById("value2").addEventListener('input', function (evt) {
value2 = +evt.target.value
});
function add() {
var added = value1 + value2;
document.getElementById("output").innerHTML = added;
}
First no:<input type="number" id="value1"><br> Second no:<input type="nunmber" id="value2"><br>
<button onclick="add()">add</button><br> output: <span id="output"></span>
添加回答
举报