动态创建DOM内容

Creating DOM content dynamically

本文关键字:内容 DOM 创建 动态      更新时间:2023-09-26

我只是在玩一些Firefox扩展程序,遇到了一个问题。假设我想创建一种网格,每条线都由很多元素组成。如果我想动态地将x行添加到面板中,我想我必须这样做:

for(var i=0; i<x; i++) {
   tempButton = document.createElement("button");
   tempLabel = document.createElement("label");
   tempWhatever = document.createElement("button");
   ...
   tempButton.setAttribute("label", "YippeYeah");
   ...
   container.appendChild(tempButton);
   container.appendChild(tempLabel);
   container.appendChild(tempWhatever);
}

这不是有点痛苦吗?思考嵌套的vbox、hbox、样式。。。用于格式化所有元素以获得良好的布局?

是否可以创建一个用户定义的.js对象,该对象由按钮、标签和Whatever的元素信息组成;然后将一个"template"-.xul文件与每个网格行关联以供重用,并只执行

for(var i=0; i<x; i++) {
   container.appendChild(myObjArray[i]);
}

建造电网不那么痛苦。

这有道理吗?还是我错了?当做Alex

是的,用DOM方法动态创建接口有点痛苦。您可能需要使用XBL。

如果你不想/不能使用XBL,你也可以使用一个模板节点并克隆它。我的文档中通常有一个节点,如下所示:

<hbox id="rowTemplate" hidden="true">
  <button class="hiButton" label="Hi!"/>
  <description class="explanation"/>
  ...
</hbox>

我创建了这样的实际行:

var container = document.getElementById("rowTemplate").cloneNode(true);
container.removeAttribute("id");
container.removeAttribute("hidden");
container.getElementsByClassName("hiButton")[0].setAttribute("foo", "bar");
container.getElementsByClassName("explanation")[0].textContent = "Try this";
...