簡體   English   中英

JavaScript / jQuery - 在輸入字段的末尾添加一個字符

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

我正在嘗試創建一個輸入字段,在輸入時自動將輸入標記放在鍵入文本的末尾。

我剛剛提出了這個代碼,但很明顯它產生了多個問號。

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

謝謝你的想法。

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

DEMO

編輯:

(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)
    }
});​

新的DEMO

// 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 += '?';
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM