2016-11-14 13 views
0

添加varible在我嘗試添加加上一個變量,它可以自我我不能看到代碼,我要去哪裏錯了:如何在它自身

<!DOCTYPE html> 
 
<html> 
 
    <body> 
 
    <h1>The * Operator</h1> 
 
    <p id="demo"></p> 
 
    <button onclick="myFunction()">Try it</button> 
 
    
 
    <script> 
 
     function myFunction() { 
 
     var playerscore = playerscore + 1; 
 
     document.getElementById("demo").innerHTML = playerscore; 
 
     } 
 
    </script> 
 
    </body> 
 
</html>

+0

首先聲明('VAR playerscore'),然後指定新的價值('playerscore = playerscore + 1;')。 – FDavidov

回答

1

您需要聲明playerscore並將其設置爲初始值,在這種情況下可能爲0。就像這樣:

<p id="demo"></p> 
 
<button onclick="myFunction()">Try it</button> 
 
<script> 
 
    var playerscore = 0; 
 

 
    function myFunction() { 
 
    playerscore = playerscore + 1; 
 
    document.getElementById("demo").innerHTML = playerscore; 
 
    } 
 
</script>

+1

OP也可以從知道用於編寫'playerscore = playerscore + 1;'的另一種(簡寫)方式'playerscore ++';' – Rounin

1

在你的函數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

0

您正試圖在初始化之前使用變量palyerscore。因此它將是未定義的,增加一個非初始化變量是毫無意義的,因此你不會在屏幕上看到任何東西。

因此,myFunction()放前更換

var playerscore = playerscore + 1; 

var playerscore = 0; 

然後裏面放myFunction

playerscore = playerscore + 1; 
+0

'抱歉,我的理解錯誤。我認爲用戶只想增加一次。 – Leo

相關問題