获取dom元素
要操作DOM首先要获取要操作的元素,可以通过dojo/dom模块的byId方法或者dojo/query的query方法。比如:
1 require([ 2 "dojo/dom", 3 "dojo/domReady!" 4 ], function(dom){ 5 6 function setText(node, text){ 7 node = dom.byId(node); 8 node.innerHTML = text; 9 } 10 11 var one = dom.byId("one"); 12 setText(one, "One has been set"); 13 setText("two", "Two has been set as well"); 14 });
创建dom元素
在Dojo中创建元素使用dojo/dom-construct模块的create方法。
该方法有四个参数,第一个参数为节点名,用string表示,第二个参数为结点属性,用object表示,第三个参数可选,为父结点或兄弟结点,第四个参数可选,为要添加的位置,默认为last。最后该方法会返回这个新的DOM元素结点。比如:
1 require([ 2 "dojo/dom", 3 "dojo/dom-construct", 4 "dojo/domReady!" 5 ],function(dom, domConstruct) { 6 7 var list = dom.byId("list"), 8 three = dom.byId("three"); 9 10 domConstruct.create("li", { 11 innerHTML: "Six" 12 }, list); 13 14 domConstruct.create("li", { 15 innerHTML: "Seven", 16 className: "seven", 17 style: { 18 fontWeight: "bold" 19 } 20 }, list); 21 22 domConstruct.create("li", { 23 innerHTML: "Three and a half" 24 }, three, "after"); 25 });
放置dom元素
如果你已经有一个结点然后想要放置这个结点,你会需要用到dojo/dom-construct模块的place方法。
该方法有三个参数,第一个参数为要放置的这个结点或结点ID值,第二个参数为待参照的结点或结点ID值,第三个参数可选,为放置的位置,默认为last。比如:
1 2 3 4 5 require([ 6 "dojo/dom", 7 "dojo/dom-construct", 8 "dojo/on", 9 "dojo/domReady!" 10 ],function(dom, domConstruct, on){ 11 12 function moveFirst(){ 13 var list = dom.byId("list"), 14 three = dom.byId("three"); 15 16 domConstruct.place(three, list, "first"); 17 } 18 19 function moveBeforeTwo(){ 20 var two = dom.byId("two"), 21 three = dom.byId("three"); 22 23 domConstruct.place(three, two, "before"); 24 } 25 26 function moveAfterFour(){ 27 var four = dom.byId("four"), 28 three = dom.byId("three"); 29 30 domConstruct.place(three, four, "after"); 31 } 32 33 function moveLast(){ 34 var list = dom.byId("list"), 35 three = dom.byId("three"); 36 37 domConstruct.place(three, list); 38 } 39 40 // Connect the buttons 41 on(dom.byId("moveFirst"), "click", moveFirst); 42 on(dom.byId("moveBeforeTwo"), "click", moveBeforeTwo); 43 on(dom.byId("moveAfterFour"), "click", moveAfterFour); 44 on(dom.byId("moveLast"), "click", moveLast); 45 });
移除dom元素
有两种方法可以移除DOM中的结点,一种为dojo/dom-construct模块的destroy方法,它可以移除该结点和所有其孩子结点,另一种为dojo/dom-construct模块的empty方法,它只是移除给定结点所有孩子结点。这两个方法的参数都只有一个,为结点或结点ID值。比如:
1 2 3 4 function destroyFirst(){ 5 var list = dom.byId("list"), 6 items = list.getElementsByTagName("li"); 7 8 if(items.length){ 9 domConstruct.destroy(items[0]); 10 } 11 } 12 function destroyAll(){ 13 domConstruct.empty("list"); 14 } 15 16 // Connect buttons to destroy elements 17 on(dom.byId("destroyFirst"), "click", destroyFirst); 18 on(dom.byId("destroyAll"), "click", destroyAll);