使用表单输入文本元素中的最后三个字符填充div?

Ism*_*ilp 2 html javascript forms jquery

我有这个代码用表单输入数据填充div:

var div = $('div')[0];
$('input').bind('keyup change', function() {
    div.innerHTML = this.value;
});
Run Code Online (Sandbox Code Playgroud)

但我只想从输入字段中提取最后三个字符而不是所有字符.如何使用jQuery实现这一目标?

感谢名单!

js-*_*der 6

您可以使用JavaScripts内置方法.substr():

var div = $('div')[0];
$('input').bind('keyup change', function() {
    var val = this.value,
        valLength = val.length;
    div.innerHTML = valLength < 3 ? val : val.substr(valLength - 3, 3);
    // check if the value has less than three chracters. If yes return the plain value, if not return the less three characters.
});
Run Code Online (Sandbox Code Playgroud)

.substr()切掉一部分字符串.它接受两个参数.第一个确定您希望子串开始的位置,第二个确定它应该多长时间.