【问题标题】:Script stops working after replacing code by var name用 var name 替换代码后脚本停止工作
【发布时间】:2017-02-23 11:08:23
【问题描述】:

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

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>

【问题讨论】:

  • getValue 是该函数的本地变量

标签: javascript


【解决方案1】:

++ 分配回其递增的值。当您声明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 甚至没有被使用。

【讨论】:

    【解决方案2】:

    getValue 是一个变量,您必须将值分配回元素。请参阅 sn-p。

    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>

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多