Select 文本与 GWT
Select text with GWT
这是 suggested answer from the Javascript SO question 我已经修改它使其成为 JSNI:
Element content = DOM.createElement("code");
select(content);
public static native void select(Element el)/*-{
var doc = $wnd.document
, text = $wnd.$(el)
, range, selection
;
if (doc.body.createTextRange) {
range = $wnd.document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if ($wnd.window.getSelection) {
selection = $wnd.window.getSelection();
range = $wnd.document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}-*/;
但是当使用时,它抛出:
caused by: com.google.gwt.core.client.JavaScriptException: (TypeError) : Argument 1 of Range.selectNodeContents does not implement interface Node.
我的代码可能有什么问题?
传递您的元素的 id
,您可以在 Javascript 代码中使用它来获取相应的 HTML 元素,并将此元素传递给您的 selectNodeContents()
javascript函数:
// Call it like this:
select(el.getId());
// And the modified select:
public static native void select(String elId)/*-{
// ...OTHER CODE OMITTED
range.selectNodeContents($wnd.document.getElementById(elId));
// ...OTHER CODE OMITTED
}-*/;
这是 suggested answer from the Javascript SO question 我已经修改它使其成为 JSNI:
Element content = DOM.createElement("code");
select(content);
public static native void select(Element el)/*-{
var doc = $wnd.document
, text = $wnd.$(el)
, range, selection
;
if (doc.body.createTextRange) {
range = $wnd.document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if ($wnd.window.getSelection) {
selection = $wnd.window.getSelection();
range = $wnd.document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}-*/;
但是当使用时,它抛出:
caused by: com.google.gwt.core.client.JavaScriptException: (TypeError) : Argument 1 of Range.selectNodeContents does not implement interface Node.
我的代码可能有什么问题?
传递您的元素的 id
,您可以在 Javascript 代码中使用它来获取相应的 HTML 元素,并将此元素传递给您的 selectNodeContents()
javascript函数:
// Call it like this:
select(el.getId());
// And the modified select:
public static native void select(String elId)/*-{
// ...OTHER CODE OMITTED
range.selectNodeContents($wnd.document.getElementById(elId));
// ...OTHER CODE OMITTED
}-*/;