javascript - 如果我设置 `let x = document.getElementById("inputText").value` 并更新 `x` ,为什么值不更新?

标签 javascript reference

在下面的示例中,为什么 ID 为 test 的输入的 value 属性没有更新为 "second"

document.getElementById("test").addEventListener("click", () => {
  let test = document.getElementById("test").value;
  
  test = "second";
  console.log(test); // Logs "second", but input value is not updated.
});
<label>Click on this test input: <input type="text" id="test" value="first"></label>

最佳答案

因为 Javascript 将 x 作为值分配,而不是对原始对象的引用。

例如,您可以改为:

function setText(x) {
    document.getElementById('test').value = x;
}

getText = function() {      
    return document.getElementById('test').value;
}

并且您使用 setText() 设置的值将被 getText() 反射(reflect)出来,因为 getText() 也会使用引用对象的值,而不是值的副本。

编辑

正如 Bryan 指出的那样,这将是一个全局范围内的引用副本:

var test = document.getElementById('test');

function setText(x) {
    test.value = x;
}

getText = function() {      
    return test.value;
}

http://jsfiddle.net/nLj2A/

原始的 test 变量存储对元素的引用,而不是与元素属性关联的值。

关于javascript - 如果我设置 `let x = document.getElementById("inputText").value` 并更新 `x` ,为什么值不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6257984/

相关文章:

javascript - 自动将文本插入表单?

javascript - 我无法将 ajax 数据保存到变量中

c - 如何正确引用 C 中的两个结构?

c++ - 奇怪的链接错误

c++ - 以下代码有什么错误?

PHP 类 : referenced variable in one method affects non-referenced variable in other method

javascript - 将 VML 代码转换为 SVG

javascript - JQuery UI 日期选择器 "dialog"在 IE8 中不起作用

rust - Rust 中的符号 '&' 和星号 '*' 是什么意思?

javascript - ,如何通过函数参数给对象命名?