动态创建 DOM 内容
我只是在玩一些 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 对象,其中包含按钮、标签和其他内容的元素信息?然后将一个“模板”-.xul 文件与每个网格行相关联以供重用,并且只执行 a
for(var i=0; i<x; i++) {
container.appendChild(myObjArray[i]);
}
即可轻松构建网格。
这有道理还是我错了? 问候, 亚历克斯
I'm just playing around with some Firefox extension programming and I came across a question. Let's say I want to create a kind of grid, each line consist of a lot of elements.
If I want to add x rows to a panel dynamically, I assume I have to do it with that:
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);
}
Isn't that a bit painful? Thinking about nested vbox, hbox, styles, ... for formatting all the elements to get a good layout?
Would it be possible to create a user defined .js object that consist of the element information for the button, the label and the Whatever; then associate a "template"-.xul file for reuse with every grid row and do only a
for(var i=0; i<x; i++) {
container.appendChild(myObjArray[i]);
}
to build the grid less painfully.
Does it make sense or am i wrong?
Regards,
Alex
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,使用 DOM 方法动态创建接口有点痛苦。您可能想使用 XBL 代替。
Yes, creating interfaces dynamically with DOM methods is kind of painful. You might want to use XBL instead.
如果您不想/无法使用 XBL,您还可以采用模板节点并克隆它。我的文档中通常有一个如下所示的节点:
我创建的实际行如下:
In cases where you don't want to/cannot use XBL you can also take a template node and clone it. I typically have a node in my document like this:
And I create the actual row like this: