2017-02-23 62 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>