JavaScript/jQuery – 在输入字段的末尾添加一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10855791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:16:55  来源:igfitidea点击:

JavaScript/jQuery – Add a character at the end of an input field

javascriptjqueryinput

提问by To E

I'm trying to make an input field which automatically puts a questionmark at the end of the typed text while typing.

我正在尝试制作一个输入字段,它在输入时自动在输入的文本末尾放置一个问号。

I just came up with this code but obviously it generates multiple questionmarks.

我刚刚想出了这段代码,但显然它会生成多个问号。

$("#id").keyup(function(){
   $(this).val($(this).val() + "?");
});

Thank you for your ideas.

谢谢你的想法。

回答by qwertymk

$("#id").keyup(function(){
    if ($(this).val().split('').pop() !== '?') {
        $(this).val($(this).val() + "?");
    }
});

DEMO

演示

EDIT:

编辑:

(function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery));
$("#id").keyup(function(){
    if ($(this).val().split('').pop() !== '?') {
        $(this).val($(this).val() + "?");
        $(this).setCursorPosition( $(this).val().length - 1)
    }
});?

new DEMO

新演示

回答by Florian Margaine

// Input is way better than keyup, although not cross-browser
// but a jquery plugin can add its support.
$('#id').on('input', function() {
    // If the last character isn't a question mark, add it
    if ( this.value[ this.value.length - 1 ] !== '?' ) {
        this.value += '?';
    }
});