在光标位置插入文本失败,空白行上 [英] Insert text at cursor position failing on blank lines

查看:52
本文介绍了在光标位置插入文本失败,空白行上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在GWT中使用此本机javascript方法在RichTextArea的光标位置插入文本.它有时可以工作,但通常会给我以下错误消息:"refNode.insertData不是函数.它似乎在光标位于空白行时发生.

I'm using this native javascript method in GWT to insert text at the cursor position of a RichTextArea. It works sometimes but often gives me this error message: "refNode.insertData is not a function. It seems to happen whenever the cursor is on a blank line.

public native void insertText(String text, int pos) /*-{
    var elem = this.@com.google.gwt.user.client.ui.UIObject::getElement()();
    var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;
    refNode.insertData(pos, text);
}-*/;

因此,我需要调试此javascript,并且不知道从哪里开始.我对javascript知之甚少,只得到了我正在使用的方法问题.我从另一个问题复制的本机方法中获得了光标位置.

So I need to debug this javascript and don't know where to begin. I know very little about javascript and only got this method I'm using off a stack question. I'm getting the cursor position from another native method I copied from this question.

我读到这个错误是因为refNode不是正确的对象类型.我以为有人会知道它实际上是什么类型的对象,并且可以帮助我处理这种情况.

I read that this error is because refNode isn't the correct type of object. I figured somebody would know what type of object it actually is and can help me handle this situation.

推荐答案

所以我认为这项工作可行.我稍微改变了Matthew的答案,它似乎在我所有的测试中都有效.当refNode等于Element类型时,我猜pos值始终是我之前需要插入的子节点元素的索引.

So I have this working I think. I changed Matthew's answer a bit and it seems to work in all my tests. When refNode equals Element type, I guess the pos value was always the index of the child node element where I needed to insert before.

public native void insertText(String text, int pos) /*-{
    var elem = this.@com.google.gwt.user.client.ui.UIObject::getElement()();
    var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer;

    if (refNode.nodeType == 1) {
        var newTextNode = document.createTextNode(text);
        refNode.insertBefore(newTextNode, refNode.childNodes[pos]);
    } else {
        refNode.insertData(pos, text);
    }
}-*/;

这篇关于在光标位置插入文本失败,空白行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆