【问题标题】:jQuery - text insert into textarea only works sometimesjQuery - 文本插入到 textarea 有时只能工作
【发布时间】:2014-03-12 04:52:40
【问题描述】:

我不清楚为什么这似乎只是偶尔起作用。

我正在尝试创建一个按钮,允许用户在光标所在位置将文本插入文本区域。只要他们没有在 textarea 中输入,它就可以工作,但是一旦他们输入,按钮就会停止工作。

脚本中的 JS 对象使用这两种方法来分割文本,然后输入它从点击按钮的“隐藏”范围中抓取的文本。

它应该从这个改变:

<newform>
    <box>
    </box>
</newform>

…在光标所在位置包含额外的框标签。

<newform>
    <box>
    </box>
    <box> //as if the cursor was here
    </box>
</newform>

其他按钮目前不起作用。这是一个更大项目的复制粘贴。

//returns an array where array[0] is text before the cursor
//and array[1] is the text after the cursor
split_at_cursor: function (element) {
    var $el = $(element).get(0);
    var split_pt = $el.selectionStart;
    return [$el.value.substring(0, split_pt), $el.value.substring(split_pt)];
},

//uses split_at_cursor to insert data at the cursor's location
insert_at_cursor: function (element, to_insert) {
    if (typeof (to_insert) !== "string") {
        //this is going to change
        to_insert = '*ERROR*';
    }
    var $el = $(element);
    $el.focus();
    var split_string = fmlpad.split_at_cursor($el);
    $el.text(split_string[0] + to_insert + split_string[1]);
},

查看完整的工作非工作示例here

我尝试了一些控制台日志记录来查看问题的性质,但它似乎总是正确地确定文本 应该 去哪里,以及插入的文本 应该 - 它并不总是真正地进行插入! :/

另外,我意识到我可能对$(some_element) 使用了太多调用,但我不确定问题是否存在,一旦应用程序变得更紧凑和更好地定义,这些问题就会出现。

【问题讨论】:

  • 你想要实现什么?你的按钮都不起作用,点击新框,新元素时你想要什么行为?

标签: jquery textarea


【解决方案1】:

需要设置文本区域的“值”,而不是“文本”。

所以,如果你改用val(),你会更幸运:

$el.val(split_string[0] + to_insert + split_string[1]);

在按下按钮后光标位置会跳转,仍然需要做一些工作,但我已经更新了 Fiddle 以显示此工作:JSFiddle

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    相关资源
    最近更新 更多