[英]assign the value of `input ` to a variable but return blank in JS
我想將input
的值分配給 Javascript 中的變量,但我不確定為什么input
的值總是空白。
這是一個例子:
let input = document.getElementById('input').value let val = 'not' function check() { //console.log(document.getElementById('input').value) will work console.log(typeof input) console.log(input) }
<input id='input' type='text'> <button onclick='check()'>Check</button>
input
值為空白(無),但typeof input
為string
。
如果我使用document.getElementById('input').value
,這將完全有效,這將成功顯示input
的值。
誰能解釋一下為什么我將它分配給一個variable
不起作用?
感謝您的任何回復!
變量賦值val = 'not'
發生在第一次頁面加載時。 當您需要分配動態值時,例如單擊按鈕時,您需要一個事件處理機制(在您的情況下,是一個click
事件)。 單擊時您正在調用 function,但沒有為您的變量分配任何值。 在 function 中進行分配,如:
function check() {
val = document.getElementById('input').value)
console.log(val)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.