2017-04-15 26 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有用户赖特的东西后,更新你的价值。