Javascript 更换按键上的字符
我有一个textarea输入元素 如果用户键入“@”,我想将其替换为@[someTextHere] 我正在使用JQuery的keypress事件,但我一直无法得到我想要的,我一直在获取字符串末尾的“@”,即[someTextHere]@ 可能吗 我的代码:Javascript 更换按键上的字符,javascript,jquery,keypress,Javascript,Jquery,Keypress,我有一个textarea输入元素 如果用户键入“@”,我想将其替换为@[someTextHere] 我正在使用JQuery的keypress事件,但我一直无法得到我想要的,我一直在获取字符串末尾的“@”,即[someTextHere]@ 可能吗 我的代码: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"
<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>
$('#post txt')。按键(函数(事件){
var str=$('#post txt').val();
if(String.fromCharCode(event.which)='@'){
$('#post txt').val(str.substring(0,str.length)+'[TEXT]';
}
})
非常感谢您的帮助。这是因为他在函数执行后添加了字符。您可以阻止添加字符,并将其添加到代码中
if(String.fromCharCode(event.which) == '@'){
event.preventDefault()
$('#post-txt').val(str + '@[TEXT]');
}
试试这个…这是一个很好的解决方案,它考虑了选择和光标位置
var replacedChar='@';
变量替换='@[SomeTextHere]'
var moveCursorBy=replacement.length-replacedChar.length//或者,如果希望光标位于“@”和“[SomeTextHere]”之间,则为0
$('textarea')。按键(功能(e){
如果(e.key==replacedChar){
//即
if(文档选择){
//确定所选文本。如果未选择文本,则返回光标在文本中的位置
var range=document.selection.createRange();
//将替换项放置在选定内容的位置上,然后删除选定内容中的数据
range.text=替换;
//铬+FF
}else if(this.selectionStart | | this.selectionStart==“0”){
//确定选择的开始和结束。
//如果未选择文本,则它们相同,并返回光标在文本中的位置
//不要将其设置为jQuery对象,因为selectionStart和selectionEnd是未知的。
var start=this.selectionStart;
var end=this.selectionEnd;
//将替换项放置在选定内容的位置上,然后删除选定内容中的数据
$(this).val($(this).val().substring(0,start)+replacement+$(this).val().substring(end,$(this).val().length));
//将光标设置回文本中的正确位置
this.selectionStart=start+moveCursorBy+1;
this.selectionEnd=start+moveCursorBy+1;
}否则{
//如果无法确定选择,
//将替换件放在末端。
$(this.val($(this.val()+替换);
}
返回false;
}
})
我冒昧地用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(',', '.');
$(“#input”).on('input keydown paste',function(){
$(this.val($(this.val()).replace(/@(?![])/g,“@[一些文本]”);
var key=event.keyCode | | event.charCode;
如果(键==8 | |键==46){
这是select();
}
});
这个正则表达式**/@(?![])/g**通过只运行一次代码,确保只有一个@与not@[在那里]匹配。
此代码还确保即使用户粘贴了@符号,他们也会在输入框中获得@[一些文本]。
此.select()确保当用户尝试使用backspace或delete按钮进行删除时,@不会再次激发(当您从“@[”中删除“[”时,正则表达式将不再能够区分,因此代码将再次激发@[某些文本]。这就是此.select()通过选择整个@[某些文本]并在swoop中将其删除来防止的)。
任何问题请在下面留言!
为什么不直接说:$('#post txt').val(str+'[TEXT]');@Tsalikidis您的解决方案不起作用。我没有声称这是一个解决方案……我只是问为什么要使用子字符串使其复杂化。如果光标不在输入框中的最后一个位置,此解决方案将无法正常工作,因为只会在末尾添加[要替换的字母]。
$(form).find('input.price').replaceCharOnKeyPress(',', '.');
<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!