在你的函數playerscore
只存在在函數內部。所以它最初將是undefined
。最簡單的(though not necessarily the best way)是在global scope中定義變量。
//outside of function now in global scope (or window.playerscore)
//set it to a value (0) also. Otherwise it's undefined. undefined +1 is not going to work
var playerscore = 0;
function myFunction() {
//no var, the varibale is declared above NOT in here Important!
playerscore = playerscore + 1;
document.getElementById("demo").innerHTML = playerscore;
}
,甚至更好的選擇是使用closure:
var myModule = (function(document){
//no longer in global scope. Scoped inside myModule so not publically accessible
var playerscore = 0;
function myFunction() {
//no var, the varibale is declared above NOT in here Important!
playerscore = playerscore + 1;
document.getElementById("demo").innerHTML = playerscore;
}
//allow myFunction to be called externally
return{myFunction:myFunction};
})(document);
HTML改變上述:
<button onclick="myModule.myFunction()">Try it</button>
雖然這可能是有點在太先進時刻。如果您對上述內容感興趣,請通讀The Revealing Module Pattern
首先聲明('VAR playerscore'),然後指定新的價值('playerscore = playerscore + 1;')。 – FDavidov