为什么变量 'a' 无法访问 document.querySelector('#b1').value 的新值


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

正如评论中所说,

当您执行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" >

相关内容

  • 没有找到相关文章

最新更新