簡體   English   中英

Javascript 值不適用於輸入文本框

[英]Javascript value not working with input text box

我環顧四周,了解如何使用 javascript 從輸入框中獲取文本,並且所有帖子都說使用 .value,但是,我一直收到“未定義”。 我認為問題是當我使用 .value 時,它​​會在輸入標簽中查找值 =“”,當它看到沒有任何值時,它會返回“未定義”

我正在嘗試獲取用戶編寫的文本並將其放入警報中。

HTML:

<input id='myText' type="text">
<input id = 'bot'type="button" value="Click Me">

JS:

var textValue = document.querySelector("#myText").value;
var clickBot = document.querySelector("#bot")

clickBot.addEventListener("click",function(){
alert(textValue)
})

如果我輸入:

<input id='myText' type="text" value = 'works'>

然后當我點擊按鈕時,我會收到一個警告說“有效”

您需要在單擊處理程序內的文本字段中獲取值; 否則,每次處理程序運行時,您都將擁有相同的值:

var clickBot = document.querySelector("#bot")

clickBot.addEventListener("click",function(){
    var textValue = document.querySelector("#myText").value;
    alert(textValue);
})

textValue變量的值在頁面加載時設置一次 由於myText輸入的值為空,因此空值將存儲在textValue變量中並保持該狀態。

為避免該問題 - 將其傳遞到函數體內以在每次click事件時刷新textValue值。

 var clickBot = document.querySelector("#bot"), textValue = document.querySelector("#myText"); clickBot.addEventListener("click", function() { alert(textValue.value); })
 <input id='myText' type="text"> <input id='bot' type="button" value="Click Me">

變量textValue已在事件偵聽器之外初始化為undefined 每次單擊該按鈕時,您都需要重新分配該值。

我建議使用textValue來存儲選擇器,然后在警報中使用textValue.value

var textValue = document.querySelector("#myText");
var clickBot = document.querySelector("#bot");

clickBot.addEventListener("click", function(){
   alert(textValue.value);
});
var myText=document.querySelector("#myText");
myText.addEventLisrener("change",function(){
   var textValue = document.querySelector("#myText").value;
});

var clickBot = document.querySelector("#bot")
clickBot.addEventListener("click",function(){
   alert(textValue);
});

在用戶更改某些內容后,您必須更新myText的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM