How to add a div dynamically by using Dojo?

荒凉一梦 提交于 2019-12-22 05:57:39

问题


I have a the following static div:

<body>
  <div id="div1"></div>
....

I want to add a div with id "div1_1" within div1 dynamically by using dojo. How can I do it?


回答1:


You can do it using just Dojo Base — no need to include anything, if you use the trunk or Dojo 1.3:

dojo.create("div", {id: "div1_1"}, "div1");

This line creates a div with id "div1_1" and appends it to the element with id "div1". Obviously you can add more attributes and styles in one go — read all about it in the documentation for dojo.create().




回答2:


Another option using flexible dojo.place:

dojo.place("<div id='div1_1'></div>", "div1", /*optional*/ "only");



回答3:


// dojo 1.7+ (AMD)
var n = domConstruct.create("div");
// dojo < 1.7
var n = dojo.create("div");



回答4:


dojo/dom-construct also can be used for creating new nodes.

A sample usage is as follows;

require([ "dojo/dom-construct", "dojo/_base/window" ], function(
        domConstruct, win) {
    // creates a new div and append it as the last child of the body
    domConstruct.create("div", null, win.body()));
});

dojo/dom-construct arguments are

  1. tag (div, h, img, li etc.)
  2. attributes ( new nodes attributes)
  3. reference node (where to place the new node)
  4. position (default last)

you can checkout the documentation for more information.




回答5:


dojo.html.set(dojo.byId("div1"), "<div id='div1_1'></div>");



回答6:


var divNode = document.createElement("div");
divNode.id = "div1_1";
document.body.appendChild( divNode );

This is a good way, it helps get past some node referencing issues in IE7 and you can continue to use the reference to the divNode later.



来源:https://stackoverflow.com/questions/687436/how-to-add-a-div-dynamically-by-using-dojo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!