gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:11:36 25 4
gpt4 key购买 nike

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

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/ - 它说

The result of the .text() method is a string containing the combined text of all matched elements.

我错过了什么?这是怎么回事?

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

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

最佳答案

获取输入值的方法是.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() 仅给出字符串值。

关于javascript - toString() 在输入时不返回字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com