我的代码有问题,我有一个“ - ”,必须在每个Enter键上插入, 这是我的jQuery和jsfiddle:
$("#textbox").on("keydown", function(e) {
if(e.which == 13){
var $this = $(this);
setTimeout(function(){
$this.insertAtCaret("- ");
}, 0);
}
提前致谢:)
答案 0 :(得分:3)
insertAtCaret
是jQuery的扩展,通常不在其中。如果您添加the extension,则可以使用:
$.fn.insertAtCaret = function(myValue) {
return this.each(function() {
var me = this;
if (document.selection) { // IE
me.focus();
sel = document.selection.createRange();
sel.text = myValue;
me.focus();
} else if (me.selectionStart || me.selectionStart == '0') { // Real browsers
var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop;
me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length);
me.focus();
me.selectionStart = startPos + myValue.length;
me.selectionEnd = startPos + myValue.length;
me.scrollTop = scrollTop;
} else {
me.value += myValue;
me.focus();
}
});
};