我需要一些澄清,因为我已经让自己感到困惑了。假设我们有以下代码:
var textarea = document.getElementById("myTextarea");
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
var words = textarea.value;
console.log(words);
}
此代码首先将 DOM 元素(按钮和文本区域)收集到各自的变量中来运行。稍后在代码中,当按下按钮时,textarea.value
被放入变量 words
中。够公平吧?
我的问题是为什么控制台没有记录任何内容? textarea 变量是在页面加载后从 DOM 创建并存储的,这可能是在用户有时间向 textarea 写入任何内容之前。这意味着 textarea.value
应等于 ''
(无),而不是用户按下按钮时文本区域中的字符串。
如果有人能为我解决这个问题,我将不胜感激。
谢谢:)
最佳答案
This would mean that
textarea.value
should equal''
(nothing), as opposed to the string in the textarea at the time that the button was pressed by the user.
不!
输入元素的 value
属性会根据用户输入或更改它的其他代码动态更新。当您访问 value
属性时,这一点很重要。因为单击按钮时访问它,所以单击按钮时会读取元素上设置的值。
但是如果你做了这样的事情:
var textarea = document.getElementById("myTextarea");
var words = document.getElementById("myButton").value;
button.addEventListener("click", function() {
console.log(words);
}
然后该值将被提前读取(可能为空,但可能是默认值、自动保存变量或之前设置的其他值),并且用户所做的更改将被忽略。
关于javascript - JS - 将 DOM 元素保存在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41072499/