在下面的示例中,为什么 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;
}
原始的 test
变量存储对元素的引用,而不是与元素属性关联的值。
关于javascript - 如果我设置 `let x = document.getElementById("inputText").value` 并更新 `x` ,为什么值不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6257984/