替换字符 OnKeyPress

Replace char OnKeyPress

我有一个文本输入元素,

如果用户键入“@”,我想将其替换为@[someTextHere]。

我正在使用 JQuery 的按键事件,但我无法得到我想要的,我一直在字符串末尾得到“@”,即[someTextHere]@.

可能吗?

我的代码:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    </head>

    <body>
        <textarea id="post-txt"></textarea>
    </body>
</html>

<script>
    $('#post-txt').keypress(function(event){
        var str = $('#post-txt').val(); 

        if(String.fromCharCode(event.which) == '@'){
            $('#post-txt').val(str.substring(0,str.length) + '[TEXT]'); 
            }
    })  
</script>

将不胜感激。

那是因为他在执行完function.you之后添加字符可以阻止添加字符,在你的代码中添加。

 if(String.fromCharCode(event.which) == '@'){
    event.preventDefault()
    $('#post-txt').val(str + '@[TEXT]'); 
 }
$(document).find('input').keypress(function(evt){ 
        if(evt.which==50){
            $(this).val($(this).val()+'[Letter to replace]');
            evt.preventDefault();
        }
    });

试试这个...

这是 kristofdegrave 的一个很好的解决方案,它考虑了选择和光标位置。

var replacedChar = '@';
var replacement = '@[SomeTextHere]'
var moveCursorBy = replacement.length - replacedChar.length; //Or 0 if you want the cursor to be after between '@' and '[SomeTextHere]'

$('textarea').keypress(function(e){
  if(e.key == replacedChar){
    // IE
    if(document.selection){
      // Determines the selected text. If no text selected, the location of the cursor in the text is returned
      var range = document.selection.createRange();
      // Place the replacement on the location of the selection, and remove the data in the selection
      range.text = replacement;
      // Chrome + FF
    } else if(this.selectionStart || this.selectionStart == '0') {
      // Determines the start and end of the selection.
      // If no text selected, they are the same and the location of the cursor in the text is returned
      // Don't make it a jQuery obj, because selectionStart and selectionEnd isn't known.
      var start = this.selectionStart;
      var end = this.selectionEnd;
      // Place the replacement on the location of the selection, and remove the data in the selection
      $(this).val($(this).val().substring(0, start) + replacement +                       $(this).val().substring(end, $(this).val().length));
      // Set the cursor back at the correct location in the text
      this.selectionStart = start + moveCursorBy + 1;
      this.selectionEnd = start + moveCursorBy + 1;
    } else {
      // if no selection could be determined,
      // place the replacement at the end.
      $(this).val($(this).val() + replacement);
    }
    return false;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea></textarea>

我冒昧地根据 Alexandru Severin 发布的函数制作了一个 jquery 函数:

$.fn.replaceCharOnKeyPress = function(chr, replacement) {
    var moveCursorBy = replacement.length - chr.length;
    this.each(function() {
        $(this).keypress(function(e) {
            if (e.key == chr) {
                // IE
                if(document.selection) {
                    // Determines the selected text. If no text selected, the location of the cursor in the text is returned
                    var range = document.selection.createRange();
                    // Place the replacement on the location of the selection, and remove the data in the selection
                    range.text = replacement;
                }
                // Chrome + FF
                else if(this.selectionStart || this.selectionStart == '0') {
                    // Determines the start and end of the selection.
                    // If no text selected, they are the same and the location of the cursor in the text is returned
                    // Don't make it a jQuery obj, because selectionStart and selectionEnd isn't known.
                    var start = this.selectionStart;
                    var end = this.selectionEnd;
                    // Place the replacement on the location of the selection, and remove the data in the selection
                    $(this).val($(this).val().substring(0, start) + replacement + $(this).val().substring(end, $(this).val().length));
                    // Set the cursor back at the correct location in the text
                    this.selectionStart = start + moveCursorBy + 1;
                    this.selectionEnd = start + moveCursorBy + 1;
                }
                else {
                    // if no selection could be determined,
                    // place the replacement at the end.
                    $(this).val($(this).val() + replacement);
                }
                return false;
            }
        });
    });
    return this;
};

用法示例:

$(form).find('input.price').replaceCharOnKeyPress(',', '.');

Live demo

<script type="text/javascript">
$("#input").on('input keydown paste', function() {
  $(this).val($(this).val().replace(/@(?![[])/g, '@[some text]'));
  var key = event.keyCode || event.charCode;
  if (key == 8 || key == 46) {
    this.select();
  }
});
</script>

This regex **/@(?![[])/g** makes sure that only a single @ is matched not @[ there by running the code only once.

This code also makes sure that even if the user pasted the @ symbol they will get @[some text] in the input box.
 
this.select() makes sure that @ will not fire again when the user tries to delete with either the backspace or delete button (when you delete '[' from '@[' the regex is no longer able to differentiate, therefore the code fires @[some text] again this is what this.select() prevents by selecting the entire @[some text] and removing it in on swoop).

Any Questions leave a comment below!