我通过下面的代码获取文本字段“Message”中最后输入的字符:
$('#message').on("keypress", function(event) {
var a= String.fromCharCode(event.which);}
我也想要得到最后一个输入字符的索引号,但是找不到任何解决方案。 我尝试了一些与indexOf和findIndex的组合,但无法使它们工作。
您可以获取它的target.SelectionStart
方法,如下所示:
null
$('#message').on("keypress", function(event) {
var a = String.fromCharCode(event.which);
console.log("Char:" + a, "Position:" + event.target.selectionStart);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="message" value=""/>