首页 > 解决方案 > 为什么变量 'a' 无法访问 document.querySelector('#b1').value 的新值

问题描述

let a = document.querySelector('#b1').value;
console.log(`a: ${a}`);
document.querySelector('#b1').value = 10;
console.log(`a: ${a}`);

标签: javascriptdom

解决方案


正如评论中所说,

当您这样做let a = document.querySelector('#b1').value; 时,它将解析该值并将其保存在变量 a 中。

所以这样做,它不会被更新。要获得实际价值,您需要每次都获得它

像这样:

let wrongWay = document.getElementById("foo").value; // Getting it the wrong way
let rightWay = document.getElementById("foo"); // Getting it the right way
console.log("wrong way value : " + wrongWay);
console.log("right way value : " + rightWay.value);

// Changing input value
document.getElementById("foo").value = "new value";
console.log("Changed value !");

console.log("wrong way value : " + wrongWay); // The value isn't updated as it is saved as a string -> so it didn't get any update
console.log("right way value : " + rightWay.value); // By getting it, you are sure to get the right value
<input id="foo" type="text" value="old value" >


推荐阅读