Javascript 用变量名替换代码后,脚本停止工作

Javascript 用变量名替换代码后,脚本停止工作,javascript,Javascript,我是个新手,刚开始学习javascript。我有两个几乎相同的脚本。第一个很好,但我想知道为什么脚本在将“document.getElementById(“counter”).value”替换为变量名“getValue”后停止工作。两者都包含相同的代码,对吗 Counter: <input type="text" id="counter" value="0"> <button onclick="myFunction()">Increase</button>

我是个新手,刚开始学习javascript。我有两个几乎相同的脚本。第一个很好,但我想知道为什么脚本在将“document.getElementById(“counter”).value”替换为变量名“getValue”后停止工作。两者都包含相同的代码,对吗

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

<button onclick="myFunction()">Increase</button>
计数器:
增加
一,


函数myFunction(){
var getValue=document.getElementById(“计数器”).value;
++document.getElementById(“计数器”).value;
}
二,


函数myFunction(){
var getValue=document.getElementById(“计数器”).value;
++getValue;
}

++
将其递增的值重新赋值。当您声明
getValue
时,这是
输入中的值的副本。需要以某种方式将其分配回
.value
属性

// given the value is "0"
function myFunction() {
    var getValue = document.getElementById("counter").value; // .value: "0"; getValue: "0"
    ++getValue; // .value "0"; getValue: 1
}
您可以通过在每个步骤中登录到控制台来轻松确认这一点


请注意,在您的第一个脚本中,
getValue
甚至没有被使用。

++
将其赋值回递增的值。当您声明
getValue
时,这是
输入中的值的副本。需要以某种方式将其分配回
.value
属性

// given the value is "0"
function myFunction() {
    var getValue = document.getElementById("counter").value; // .value: "0"; getValue: "0"
    ++getValue; // .value "0"; getValue: 1
}
您可以通过在每个步骤中登录到控制台来轻松确认这一点


请注意,在第一个脚本中,甚至没有使用
getValue

getValue是一个变量,您必须将该值赋回元素。请参阅代码片段

函数myFunction(){
var getValue=document.getElementById(“计数器”).value;
++getValue;
document.getElementById('counter')。value=getValue;
}


+
getValue是一个变量,您必须将该值赋回元素。请参阅代码片段

函数myFunction(){
var getValue=document.getElementById(“计数器”).value;
++getValue;
document.getElementById('counter')。value=getValue;
}


+
getValue对于该函数是本地的getValue对于该函数是本地的
// given the value is "0"
function myFunction() {
    var getValue = document.getElementById("counter").value; // .value: "0"; getValue: "0"
    ++getValue; // .value "0"; getValue: 1
}