[英]document.getElementById().value doesn't return the right value
[英]document.getElementById('url_input').value doesn't print the value
我正在嘗試通過以下代碼獲取文本輸入的值:
var input = document.getElementById('url_input').value;
和
document.getElementById("send_url").onclick = function(){
console.log(input);
}
這不起作用,但是如果我這樣改變:
var input = document.getElementById('url_input');
document.getElementById("send_url").onclick = function(){
console.log(input.value);
}
兩者有什么不同? 為什么第一個不起作用?
因為當您讀取.value時,它就是當時的值。 屬性更改時,它不會一直更新變量。
所以當你這樣做
var input = document.getElementById('url_input').value
如果在該時刻存儲該值,則該值將在變量中。
兩者有什么不同?
在第一個示例中, 將值復制到input
:
var input = document.getElementById('url_input').value;
然后反復重新記錄該值:
document.getElementById("send_url").onclick = function(){
console.log(input);
}
將值復制到input
中不會在input
和HTMLInputElement
的value
屬性之間創建任何形式的持續鏈接。 它只是從那行代碼進入input
時開始復制value的value
。
在第二個示例中,您每次都從HTMLInputElement
獲取值:
var input = document.getElementById('url_input');
document.getElementById("send_url").onclick = function(){
console.log(input.value);
}
每次單擊時,您都在詢問HTMLInputElement
當前狀態。 請注意, input
的值在兩次點擊之間仍然保持不變; 它是對url_input
元素(這是一個對象)的引用,並且此引用在此代碼中沒有更改。 更改的是對象( HTMLInputElement
)的狀態 ,您每次都在詢問其當前狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.