Replace char OnKeyPress

I have a textarea input element,

If the user types "@" I want to replace it with @[someTextHere].

I'm using JQuery's keypress event, but I havent been able to get what I want, I keep getting the "@" at the end of the string , Ie [someTextHere]@.

Is it possible?

My Code:

<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>

Assistance would be appreciated.


这是因为他在执行函数后添加了字符。您可以防止添加字符并将其添加到代码中。

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

尝试这个...

链接地址: http://www.djcxy.com/p/26022.html

上一篇: LINQ to Entities中的SQL排名

下一篇: 替换char OnKeyPress