在这个教程中,你将会学习到在跨浏览器下用Dojo操作 DOM. 使用基本的DOM知识和几个Dojo函数, 你将可以有效的创建,读取,删除一个页面的元素。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Demo: DOM Functions</title> <script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.2/dojo/dojo.js" data-dojo-config="async: true"> </script> <script> require(["dojo/domReady!"], function() { }); </script> </head> <body> <ul id="list"> <li id="one">One</li> <li id="two">Two</li> <li id="three">Three</li> <li id="four">Four</li> <li id="five">Five</li> </ul> </body> </html>
// Require the DOM resource require(["dojo/dom", "dojo/domReady!"], function(dom) { function setText(node, text){ node = dom.byId(node); node.innerHTML = text; } var one = dom.byId("one"); setText(one, "One has been set"); setText("two", "Two has been set as well"); });
require(["dojo/dom", "dojo/dom-construct", "dojo/domReady!"], function(dom, domConstruct) { var list = dom.byId("list"), three = dom.byId("three"); domConstruct.create("li", { innerHTML: "Six" }, list); domConstruct.create("li", { innerHTML: "Seven", className: "seven", style: { fontWeight: "bold" } }, list); domConstruct.create("li", { innerHTML: "Three and a half" }, three, "after"); });
<button id="moveFirst">The first item</button> <button id="moveBeforeTwo">Before Two</button> <button id="moveAfterFour">After Four</button> <button id="moveLast">The last item</button>
require(["dojo/dom", "dojo/dom-construct", "dojo/on", "dojo/domReady!"], function(dom, domConstruct, on){ function moveFirst(){ var list = dom.byId("list"), three = dom.byId("three"); domConstruct.place(three, list, "first"); } function moveBeforeTwo(){ var two = dom.byId("two"), three = dom.byId("three"); domConstruct.place(three, two, "before"); } function moveAfterFour(){ var four = dom.byId("four"), three = dom.byId("three"); domConstruct.place(three, four, "after"); } function moveLast(){ var list = dom.byId("list"), three = dom.byId("three"); domConstruct.place(three, list); } // Connect the buttons on(dom.byId("moveFirst"), "click", moveFirst); on(dom.byId("moveBeforeTwo"), "click", moveBeforeTwo); on(dom.byId("moveAfterFour"), "click", moveAfterFour); on(dom.byId("moveLast"), "click", moveLast); });
<button id="destroyFirst">Destroy the first list item</button> <button id="destroyAll">Destroy all list items</button>
function destroyFirst(){ var list = dom.byId("list"), items = list.getElementsByTagName("li"); if(items.length){ domConstruct.destroy(items[0]); } } function destroyAll(){ domConstruct.empty("list"); } // Connect buttons to destroy elements on(dom.byId("destroyFirst"), "click", destroyFirst); on(dom.byId("destroyAll"), "click", destroyAll);