我希望每次在输入字段中输入内容时都返回一个字符串。换句话说,每次按键时,我都希望在控制台中看到它被输入。所以在输入中输入堆栈,我想看看:
s
st
sta
stac
stack
我的初始代码是:
$("#input").on('input', function() {
var userInput = $(this).text();
console.log(userInput);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
哪个空白。好的,我们试试toString()
:
$("#input").on('input', function() {
var userInput = $(this).text();
console.log(userInput.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
结果相同。为什么?不toString()
将数据类型转换为字符串,不应将其记录在控制台中。
为什么在没有toString()
的第一个例子中它不返回文本值?
http://api.jquery.com/text/ - 它说
.text()方法的结果是一个包含所有匹配元素的组合文本的字符串。
我错过了什么?这是怎么回事?
编辑:愚蠢的错误,我需要.val();
,但这引出了另一个问题:
如果.text()
返回字符串,控制台是否为空?
答案 0 :(得分:7)
获取输入值的方法是.val()
而不是.text()
。请参阅以下应用程序:
$("#input").on('input', function() {
var userInput = $(this).val();
console.log(userInput);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
您基本上不需要.toString()
,因为.val()
仅提供字符串值。
答案 1 :(得分:3)
你真是太近了! .text()用于innerText
类型的东西。你正在寻找的是.val()
从收获中获得的价值。
$("#input").on('input', function() {
var userInput = $(this).val();
console.log(userInput.toString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
答案 2 :(得分:1)
改为使用val()
功能。
希望这就是你要找的东西。如果需要,很乐意解释或帮助提供更好的解决方案。
$("#input").on('input', function() {
var userInput = $(this).val();
console.log( userInput);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
答案 3 :(得分:0)
如果您要做的只是回显值,则不需要jQuery对象。您可以使用this.value
。
$("#input").on('input', function() {
console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">