javascript - 为什么变量 '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" >
推荐阅读
- java - 无法使用 springdoc-openapi-ui 打开 swagger-ui.html
- reactjs - 覆盖材质 UI 样式的问题
- python - Keras batch_dot 执行中的编译错误:
- elasticsearch - 使用休眠搜索和休眠 ORM 特例进行索引映射
- c# - 如何编辑 SOAP 请求正文
- java - 为什么我在运行测试代码时收到此消息(设置 -DfailIfNoTests=false 以忽略此错误。)?
- javascript - 使用 Spring Boot 和 React Router 提供静态文件夹
- reactjs - 更新数组变量的状态
- ios - Peer 删除了 react-native-ble-plx 中的配对信息
- r - 输出循环 Ggplot2 数字到 pdf:下标越界