GWT和JSNI将Javascript按钮添加到HTML面板中

时间:2012-12-30 09:57:03

标签: java javascript gwt jsni

我创建了一个包含简单按钮的简单Javascript文件。

function testfuncion() {
    document.write('<input type="button" name="hello" value="hello">');
}

然后我在gwt中创建了一个HTML面板。

HTML panelHtmlTry = new HTML();

如何将Javascript按钮放入HTML面板?

在这个实验中,我不能在gwt中创建按钮,而只是将一个Javascript对象放入gwt面板。

PS:我可以使用html面板或horizzontal面板。我的目标是在每个GWT面板上放置一个javascript按钮并显示它

3 个答案:

答案 0 :(得分:1)

是的,有一种更简单的方法可以做你想要的。但如果你想做你想做的事。您可以通过JSNI调用自定义JavaScript方法。

此JSNI方法调用您的自定义JS脚本,该脚本包含在主机页面中。

private native void testfunction() /*-{
  $wnd.testfuncion();
}-*/;

$ wnd是对浏览器window对象的引用,请参阅GWT Docs on JSNI

然后,您可以在GWT代码中的任何位置调用此JSNI方法:

testfunction();

每次,文件中的JavaScript函数都会通过JSNI调用。


您可以暂时重新标记document.write,以便在您希望的HTML小部件中设置按钮。

private native void testfunction(HTML html) /*-{
  var originalWriteFunc = $wnd.document.write;
  $wnd.document.write = function(str) {
    html.@com.google.gwt.user.client.ui.HTML::setHTML(Ljava/lang/String;)(str);
  };

  $wnd.testfuncion();
  $wnd.document.write = originalWriteFunc;
}-*/;

因此,您需要使用HTML小部件调用testfunction,其中应该放置按钮。

答案 1 :(得分:1)

鉴于不允许对JS文件进行任何修改,并假设input 是文档中唯一的input ,您可以将HTML扩展为包装input元素:

public class MyInputHtml extends HTML {

    public MyInputHtml() {

        // initialize DOM with external script content
        testfunction();

        // set the DOM element as the widget's element
        Element body = RootPanel.get().getElement();
        Element el = body.getElementsByTagName("input").getItem(0);
        setElement(el);
    }

    private native void testfunction() /*-{
        $wnd.testfuncion();
    }-*/;
}

当然,如果您为input分配id,那将是最好的。这样,您只需调用RootPanel.get(id)即可查找,从而避免了对基于索引的搜索的需要。这将增强您的代码,因为DOM中的更改不会影响此查找。

答案 2 :(得分:0)

让你的testFunction返回一个字符串。这可以插入你的panelHtmlTry。