本文共 1820 字,大约阅读时间需要 6 分钟。
dom5秒计时截断
While working with the students in my bootcamp I helped a few of them navigate one problem: timing.
与我的训练营中的学生一起工作时,我帮助了一些人解决了一个问题:时间安排。
In particular, there’s one thing that might not be apparent at first.
特别是,有一件事一开始可能并不明显。
When you access the value of a DOM element and you store it into a variable, that variable is NOT going to be updated with the new value when the DOM element changes.
当您访问DOM元素的值并将其存储到变量中时,当DOM元素更改时,该变量将不会使用新值进行更新。
Suppose you have an input field in a form <input id="temperature">
, and you get its value in this way:
假设您有一个格式为<input id="temperature">
的输入字段,并且可以通过以下方式获取其值:
const temperature = document.querySelector('input#temperature').value
The temperature
variable gets the value of the state of the input field at the moment the browser executes this statement, and then the value stays the same forever.
temperature
变量在浏览器执行此语句时获取输入字段的状态值,然后该值永远保持不变。
This is why you can’t do like this:
这就是为什么您不能这样做:
const temperature = document.querySelector('input#temperature').valuedocument.querySelector('form') .addEventListener('submit', event => { //send the temperature value to your server})
but you need to access the temperature value when you submit the form:
但提交表格时,您需要访问温度值:
document.querySelector('form') .addEventListener('submit', event => { const temperature = document.querySelector('input#temperature').value //send the temperature value to your server})
Alternatively you can store the input field reference in a variable, and use that to access its value at submit:
或者,您可以将输入字段引用存储在变量中,并使用该变量在提交时访问其值:
const temperatureElement = document.querySelector('input#temperature')document.querySelector('form') .addEventListener('submit', event => { const temperature = temperatureElement.value //send the temperature value to your server})
翻译自:
dom5秒计时截断
转载地址:http://yamgb.baihongyu.com/