2017-02-23 47 views
0

我是新手,剛開始學習javascript。我有兩個幾乎相同的腳本。這第一個工作正常,但我想知道爲什麼腳本在替換「document.getElementById(」counter「).value」var name「getValue」後停止工作。兩者都包含相同的代碼,對吧?通過var名稱替換代碼後腳本停止工作

Counter: <input type="text" id="counter" value="0"> 

<button onclick="myFunction()">Increase</button> 

1.

<script> 
function myFunction() { 
    var getValue = document.getElementById("counter").value; 
    ++document.getElementById("counter").value; 
} 
</script> 

2.

<script> 
function myFunction() { 
    var getValue = document.getElementById("counter").value; 
    ++getValue; 
} 
</script> 
+0

的getValue是局部的功能 – Satya

回答

5

++分配回值,其遞增。當您聲明getValue時,即爲input中的值的副本。它需要以某種方式分配回.value屬性。

// given the value is "0" 
function myFunction() { 
    var getValue = document.getElementById("counter").value; // .value: "0"; getValue: "0" 
    ++getValue; // .value "0"; getValue: 1 
} 

您可以輕鬆地通過登錄控制檯的每一步來確認這一點。

請注意,在您的第一個腳本中,getValue甚至沒有被使用。

0

getValue是一個變量,您必須將該值分配回元素。查看片段。

function myFunction() { 
 
    var getValue = document.getElementById("counter").value; 
 
    ++getValue; 
 
    document.getElementById('counter').value=getValue; 
 
}
<input type="text" id="counter" value=0 /> 
 
<button onclick="myFunction();">+</button>