将 `input` 的值赋给一个变量,但在 JS 中 return 为空
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 check() {
val = document.getElementById('input').value
console.log(val)
}
我想将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 check() {
val = document.getElementById('input').value
console.log(val)
}