0

我的代码有些问题,我有一个“-”,必须在每个 Enter 键上插入,这是我的 jQuery 和 jsfiddle:

$("#textbox").on("keydown", function(e) {
      if(e.which == 13){
        var $this = $(this);
        setTimeout(function(){
          $this.insertAtCaret("- ");
        }, 0);
      }

http://jsfiddle.net/npGVS/

提前致谢 :)

4

1 回答 1

3

insertAtCaret是 jQuery 的扩展,通常不在其中。如果您添加扩展名,它可以工作:

演示

$.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();
        }
    });
};
于 2013-05-30T10:02:22.420 回答