gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 05:07:34 25 4
gpt4 key购买 nike

在下面的示例中,为什么 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com