如何在javascript中插入元素到HTML结构中

How to insert element into HTML structure in javascript

本文关键字:HTML 结构 元素 插入 javascript      更新时间:2023-09-26

从我的小部件编译GWT客户端后,我得到以下结构:

<td align="left" width="100%" class="gwt-TabBarRest-wrapper" style="vertical-align: bottom;"><div class="gwt-TabBarRest" style="white-space: normal; height: 100%;">&nbsp;</div></td>

我如何把按钮元素而不是&nbsp;有这个结构:

<td align="left" width="100%" class="gwt-TabBarRest-wrapper" style="vertical-align: bottom;"><div class="gwt-TabBarRest" style="white-space: normal; height: 100%;"><button type="button" class="gwt-Button helpButton"></div></td>

应该这样做:

    ButtonElement buttonEl = DOM.createButton().cast();
    buttonEl.setInnerHTML("MyButton01");
    Element el = DOM.getElementById("myButtonPlace");
    el.appendChild(buttonEl);
    DOM.sinkEvents(el, Event.ONCLICK | Event.ONMOUSEOVER);
    DOM.sinkEvents(buttonEl, Event.ONCLICK | Event.ONMOUSEOVER);
    DOM.setEventListener(buttonEl,
                         new EventListener() {
                            @Override
                            public void onBrowserEvent(Event event) {
                                GWT.debugger();
                                switch (DOM.eventGetType(event)) {
                                    case Event.ONCLICK: GWT.log("you clicked the button");
                                    break;
                                    case Event.ONMOUSEOVER: GWT.log("the mouse is over the button");
                                    break;
                                }
                            }
                        });

首先为div设置一个Id

你的html现在看起来像这样

<td align="left" width="100%" class="gwt-TabBarRest-wrapper" style="vertical-align: bottom;"><div id="some_id" class="gwt-TabBarRest" style="white-space: normal; height: 100%;">&nbsp;</div></td>

现在使用下面的代码片段:

Button button = new Button();
....
....
RootPanel.get("some_id").add(button);

你可以在JQuery中使用。HTML方法来设置HTML元素的内容。

$("div.gwt-TabBarRest").html('<button type="button" class="gwt-Button helpButton"></button>');