2017-04-15 88 views
0

我環顧四周如何從一個輸入框中使用JavaScript抓取文本和所有帖子說使用.value,但是,我不斷收到「undefined」。我認爲問題是當我使用.value時,它在輸入標籤中查找value =「」,並且當它看到沒有任何東西讓我回到「undefined」時我試圖抓取用戶寫入的文本並將其置於警報中。Javascript的價值不工作與輸入文本框

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'> 

然後當我點擊按鈕,我會得到一個警告說 「作品」

回答

1

您需要獲取點擊處理程序內的文本字段;否則,你只是在每次處理程序運行時有相同的價值:

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

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

非常感謝,我不能相信那是問題 – Paul

+0

保羅好心地把這個標記爲答案,如果它解決了你的問題。謝謝 –

0

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">

+1

謝謝,我一個小時試圖弄清楚我的腦袋,我感到非常愚蠢 – Paul

1

可變textValue已初始化爲undefined事件監聽器的外部。 每次單擊該按鈕時都需要重新分配該值。

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

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

clickBot.addEventListener("click", function(){ 
    alert(textValue.value); 
}); 
0
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有用戶賴特的東西后,更新你的價值。