【问题标题】:why variable 'a' is not able to access the new value of document.querySelector('#b1').value为什么变量 'a' 无法访问 document.querySelector('#b1').value 的新值
【发布时间】:2021-11-30 18:37:22
【问题描述】:
let a = document.querySelector('#b1').value;
console.log(`a: ${a}`);
document.querySelector('#b1').value = 10;
console.log(`a: ${a}`);

【问题讨论】:

标签: javascript dom


【解决方案1】:

正如 cmets 中所说,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 2017-02-11
    • 2020-06-20
    相关资源
    最近更新 更多