toString()不会在输入时返回字符串值

kaw*_*nah 0 html javascript jquery

每次在输入字段中输入内容时,我想返回一个字符串.换句话说,每次按键时,我都希望在控制台中看到它被输入.所以在输入中输入堆栈,我想看到:

s
st
sta
stac
stack
Run Code Online (Sandbox Code Playgroud)

我的初始代码是:

$("#input").on('input', function() {
    var userInput = $(this).text();
    console.log(userInput);
  });
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
Run Code Online (Sandbox Code Playgroud)

哪个是空白的.好的,让我们试试toString():

$("#input").on('input', function() {
    var userInput = $(this).text();
    console.log(userInput.toString());
  });
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
Run Code Online (Sandbox Code Playgroud)

结果相同.为什么?不toString()将数据类型转换为字符串,不应将其记录在控制台中.

为什么在第一个例子中没有toString()它不返回文本值?

http://api.jquery.com/text/ - 它说

.text()方法的结果是一个包含所有匹配元素的组合文本的字符串.

我错过了什么?这里发生了什么?

编辑:愚蠢的错误,我需要,.val();但这导致我另一个问题:

如果.text()返回一个字符串,控制台是否为空?

voi*_*oid 7

方法来获取值的输入.val(),而不是.text().请参阅以下应用程序:

$("#input").on('input', function() {
  var userInput = $(this).val();
  console.log(userInput);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="input" placeholder="type">
Run Code Online (Sandbox Code Playgroud)

你基本上不需要.toString()因为.val()只给字符串值.