我正在尝试在javascript对象中提取表单输入的值,但该值未在console.log中返回,它不返回文本。但是,当我在Chrome控制台中定义确切的代码(“var sub”)时,它可以正常工作并返回值。
-------------------- HTML -----------------------
<div id="form2">
<form action="">
<h2>Where are you moving to?</h2>
<label for="">Collection</label>
<input id="lol" type="text">
<label for="">Delivery</label>
<input type="text">
<button type="button" name="button">Step 3</button>
</form>
</div>
--------------的JavaScript -----------------------
var submit2 = document.querySelector("#form2 > form > button");
var sub = document.querySelector("#lol").value;
var customer = [];
submit2.addEventListener("click", function() {
console.log("clicked");``
console.log(sub);
})
------------------------ Chrome控制台-------------------- < / p>
clicked
style.js:6
sub
""
var sub = document.querySelector("#lol").value;
undefined
sub
"adsf"
答案 0 :(得分:0)
请记住,字符串是原始值,在对象外部,它将作为值而不是引用传递(请参阅此处的解释https://snook.ca/archives/javascript/javascript_pass)
当浏览器加载页面时,它将评估所有命令:
var submit2 = document.querySelector("#form2 > form > button");
/* var submit2 = Dom reference object button */
var sub = document.querySelector("#lol").value;
/* sub = fixed empty string (the initial value of the input when the page loads) */
var customer = [];
submit2.addEventListener("click",
function() {
console.log("clicked");
console.log(sub);
/* when this function runs, sub.value evaluate the empty string of sub variable instead of get the new value property of #lol */
}
)
尝试更改为对象的引用而不是值:
var submit2 = document.querySelector("#form2 > form > button");
/* var sub = document.querySelector("#lol").value; */
var sub = document.querySelector("#lol");
/* sub = #lol DOM object reference */
var customer = [];
submit2.addEventListener("click",
function() {
console.log("clicked");
/* console.log(sub); */
console.log(sub.value);
/* sub.value= new string of #lol object */
}
)
答案 1 :(得分:0)
这是正确答案:
javascript 应该等待,直到 DOM 完全加载。
window.addEventListener('DOMContentLoaded', start);
function start() {
console.log('DOM fully loaded and parsed');
// your code
}
大多数人会使用 'load' 事件,但它不如 DOMContentLoaded 事件有效。