jquery - 我的代码有问题,我有一个 "-",必须在每个 Enter 键上插入

标签 jquery html css

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

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

http://jsfiddle.net/npGVS/

提前致谢:)

最佳答案

insertAtCaret 是 jQuery 的扩展,通常不在其中。如果你加入 the extension , 它有效:

DEMO

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

关于jquery - 我的代码有问题,我有一个 "-",必须在每个 Enter 键上插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16833156/

相关文章:

html - Flexbox 垂直填充可用空间

javascript - 尝试使用 JS 依次运行一个函数

html - 响应式设计不适用于 linux cpanel (GoDaddy) - 适用于 classis linux 主机 (GoDaddy) 和本地

javascript - Jquery 幻灯片中的图片断断续续且显示不正确

jquery - 使平均菜单位置固定

javascript - JQuery 嵌套列表过滤器 - 当父级匹配时显示所有子级

jquery - 随着时间的推移用 CSS/jQuery 填充圆圈的背景颜色

jquery - 将表单中的输入保存到列表中。

jquery - Wordpress 中的 SCRIPT5 : Access Denied on IE9 due to jQuery. 分钟 CDN 文件

javascript - 使用 intercom.js 在单独的窗口上触发功能