dojo是怎么加载html的,dojo之html(dom)fragment常用操作

1.dojo.html

dojo.html.set(node, cont, params) inserts (replaces) the given

content into the given node. dojo.place(cont, node, "only") may be

a better choice for simple HTML insertion.

dojo.html.set( node, cont, params)

dojo.html.setDefined by dojo.html

Unless you need to use the params capabilities of this method, you

should use dojo.place(cont, node, "only"). dojo.place() has more

robust support for injecting an HTML string into the DOM, but it

only handles inserting an HTML string as DOM elements, or inserting

a DOM node. dojo.place does not handle NodeList insertions or the

other capabilities as defined by the params object for this

method.

Parameter Type Description

node DomNode the parent element that will receive the content

cont String|DomNode|NodeList the content to be set on the parent

element. This can be an html string, a node reference or a

NodeList, dojo.NodeList, Array or other enumerable list of

nodes

params Object Optional.

Optional flags/properties to configure the content-setting. See

dojo.html._ContentSetter

example1:

A safe string/node/nodelist content replacement/injection with

hooks for extension Example Usage: dojo.html.set(node, "some

string"); dojo.html.set(node, contentNode, {options});

dojo.html.set(node, myNode.childNodes, {options});

example2:

Click to set

content

Nothing

here

yet

dojo.require("dojo.html");

var

sethandle = dojo.connect(dojo.byId("setbtn"), "onclick",

function(){

dojo.html.set(dojo.byId("mytable"),

'

'

+'

How

much?

'

+'

type="text" data-dojo-type="dijit.form.NumberTextBox"

value="0"'

+ ' constraints="{min:0, max:20,

places:0}"'

+ ' promptMessage= "Enter a value between 0 and

+20"'

+ ' required= "true" invalidMessage= "Wrong!"

/>'

+'

'

+'

', {

parseContent: true,

onBegin: function(){

dojo.require('dijit.form.NumberTextBox');

this.inherited("onBegin", arguments);

}

});

dojo.disconnect(sethandle);

sethandle = null;

dojo.byId("setbtn").innerHTML = "Done";

});

例如:

dojo.require("dijit.form.DateTextBox");

dojo.require("dojo.html");

function

test(){

var inputObj

= '

dojoType="dijit.form.DateTextBox"

hasDownArrow="false"/>';

//dojo.place(inputObj,dojo.byId("xxForm"));

dojo.html.set(dojo.byId("xxForm"),inputObj,{

parseContent: true,

onBegin: function(){

dojo.require('dijit.form.DateTextBox');

this.inherited("onBegin", arguments);

}

});

}

2.dojo.placedojo.place(node, refNode,

pos):

(1)node

Can be a String or a DOM node. If it is a string starting with

will be created. Otherwise it is assumed to be an id of a DOM

node.

Note:

An HTML fragment can have more than one top node.

In the case of an invalid HTML fragment the result of instantiation

is undefined.

When instantiating an HTML fragment the owner document of the

reference node is used.

(2)refNode

Can be a string (interpreted as an id of a DOM node) or a DOM

node.

(3)pos

Optional argument. Can be a number or one of the following strings:

“before”, “after”, “replace”, “only”, “first”, or “last”. If

omitted, “last” is assumed. The value of “only” replaces all

children of the refNode.

If the position argument is a number, it indicates that the node

should be inserted as a child of refNode with this number (counting

from 0).

If pos is a number, the node will be placed as a child of the

reference node with this number (counting from 0). For example, if

3 is specified,

the node will be placed as the 3rd child (0, 1, 2, and 3 will be

our node) assuming that the reference node has at least three

existing children.

If the number is more than number of children, the node will be

appended to the reference node making it the last child. If the

number is less than 0,

the node will be placed at position 0 making it the first child of

the reference node.

The naming of the positions are intentionally concise.

place returns the node it placed. In case of an HTML fragment, if

it has just one root element, that element is returned directly.

Otherwise a document fragment is returned. The returned node can

be:

A regular DOM element node: nodeType is 1 for ELEMENT_NODE ,

example:

42
”.

See DOM Core Level 1: Element for more details.

A document fragment representing a group of nodes: nodeType is 11

for DOCUMENT_FRAGMENT, example:

1st

paragraph

2nd

paragraph

”.

See DOM Core Level 1: DocumentFragment for more details.

The document fragment is a very useful tool to work with a group of

arbitrary nodes, because standard DOM methods can work with it as

with a regular node operating on the whole group, e.g., inserting

or appending it as a whole.

Note that DocumentFragment is a Node, but not an Element. It does

not support innerHTML, style, or any other familiar attributes of

the element.

example:

dojo.ready(function(){

var n = 0;

dojo.connect(dojo.byId("placeFLO"), "onclick",

function(){

dojo.place("

new

node #" + (++n) + "

",

"refFLO",

dojo.byId("posFLO").value); // first/last/only

});

});

id="placeFLO">Place

node

id="posFLO">

value="first">first

value="last">last

value="only">only

before:

1st

before:

2nd

class="ref">

the reference

node's child #0

the reference

node's child #1

the reference

node's child #2

after:

1st

after:

2nd

div.ref { background-color: #fcc; }

div.node {

background-color: #cfc; }

div.child { background-color:

#ffc; }

div.ref div { margin-left: 3em; }

简要说明:

(1)before、after

这两个选项把节点作为参考节点的父节点的子节点来放置。”before” 声明把节点放置在参考节点之前,而 “after”

声明把节点放置在参考节点之后。

parent.insertBefore(node, ref);

parent.insertBefore(node, ref.nextSibling);

(2)replace 声明用节点的内容替换掉参考节点的内容。

(3)first、last、only

这3个选项把节点作为参考节点的子节点来放置。”first” 声明放置为第一个子节点, “last”

声明放置为最后一个子节点,

“only” 声明替换掉参考节点的所有子节点

(4)number

如果 pos

是数字的话,节点作为参考节点的子节点来放置,该数字的值作为在参考节点子节点列表中的序号。例如,如果值是3的话,节点作为第四个子节点来放置。

如果该数字的值超过了参考节点的子节点的个数的话,节点作为参考节点的最后一个子节点。如果该数字的值小于0,则节点作为参考节点的第一个子节点来放置。

3.dojo.toDominstantiates an HTML fragment

returning the corresponding DOM.

dojo.toDom( frag, doc)

frag String:the HTML fragment

doc DocumentNode:optional document to use when creating DOM nodes,

defaults to dojo.doc if not specified.

var tr =

dojo.toDom("

First!");

4.dojo.string.substitutePerforms

parameterized substitutions on a string. Throws an exception if any

parameter is unmatched.

参数介绍:

template:a string with expressions in the form ${key} to be

replaced or ${key:format} which specifies a format function. keys

are case-sensitive.

map:类型是Object|Array, hash to search for substitutions

transform:Function Optional.

a function to process all parameters before substitution takes

place, e.g. mylib.encodeXML

thisObject:where to look for optional format function; default to

the global namespace

Example 1

Substitutes two expressions in a string from an Array or

Object

// returns "File 'foo.html' is not found in directory

'/temp'."

// by providing substitution data in an Array

dojo.string.substitute(

"File '${0}' is not found in directory

'${1}'.",

["foo.html","/temp"]

);

// also returns "File 'foo.html' is not found in directory

'/temp'."

// but provides substitution data in an Object

structure. Dotted

// notation may be used to traverse the structure.

dojo.string.substitute(

"File '${name}' is not found in directory

'${info.dir}'.",

{ name: "foo.html", info: { dir: "/temp" }

}

);

Example 2

Use a transform function to modify the values:

// returns "file 'foo.html' is not found in directory

'/temp'."

dojo.string.substitute(

"${0} is not found in ${1}.",

["foo.html","/temp"],

function(str){

// try to figure out the

type

var prefix = (str.charAt(0) ==

"/") ? "directory": "file";

return prefix + " '" + str +

"'";

}

);

Example 3

Use a formatter

// returns "thinger -- howdy"

dojo.string.substitute(

"${0:postfix}", ["thinger"], null, {

postfix: function(value,

key){

return value

+ " -- howdy";

}

}

);

5.placeAt()

xxWidget.placeAt('xx');

var foo=dijit._Widget.placeAt(reference: String|DomNode|_Widget,

position: String?|Integer?); (view source)

reference String|DomNode|_Widget The String id of a domNode, a

domNode reference, or a reference to a Widget posessing an addChild

method.

position String?|Integer Optional. If passed a string or domNode

reference, the position argument accepts a string just as

dojo.place does, one of: "first", "last", "before", or "after". If

passed a _Widget reference, and that widget reference has an

".addChild" method, it will be called passing this widget instance

into that method, supplying the optional position index passed.

// create a Button with no srcNodeRef, and place it in the

body:

var button = new dijit.form.Button({ label:"click"

}).placeAt(dojo.body());

// now, 'button' is still the widget reference to the newly created

button

dojo.connect(button, "onClick", function(e){ console.log('click');

});

Example 2

// create a button out of a node with id="src" and append it to

id="wrapper":

var button = new

dijit.form.Button({},"src").placeAt("wrapper");Example 3

// place a new button as the first element of some div

var button = new dijit.form.Button({ label:"click"

}).placeAt("wrapper","first");Example 4

// create a contentpane and add it to a TabContainer

var tc = dijit.byId("myTabs");

new dijit.layout.ContentPane({ href:"foo.html", title:"Wow!"

}).placeAt(tc)

6.开发中常用操作(1) 服务器端返回的是 JSON 格式的数据,在浏览器端使用

dojo.create()来执行 DOM 操作

dojo.xhrGet({

url : "/posts",

load : function(data) {

var container = dojo.byId("posts");

for (var i = 0, n = data.length; i 

var post = data[i];

var postNode = dojo.create("div", {

className : "post"

}, container);

dojo.create("div", {

className : "title",

innerHTML : post.title

}, postNode);

dojo.create("div", {

className : "content",

innerHTML : post.content

}, postNode);

}

},

error : function() {

dojo.html.set(dojo.byId("posts"), "获取文章出错。");

}

});

(2) 服务器端返回数据,浏览器端使用模板

var template = "

${title}
"

+ "

${content}
";

dojo.xhrGet({

url : "/posts",

load : function(data) {

var container = dojo.byId("posts");

for (var i = 0, n = data.length; i 

var node = dojo.create("div", {

innerHTML : dojo.string.substitute(template, data[i]);

});

container.a(node.firstChild);

}

},

error : function() {

dojo.html.set(dojo.byId("posts"), "获取文章出错。");

}

});

(3) 使用文档片段:

文档片段是一个轻量级的文档对象,可以用来包含其它节点。当文档片段被插入到文档树中的时候其本身并不会被插入而只有其子节点被插入。一个常见的提高

DOM 操作性能的做法是

利用文档片段来插入新创建的节点。首先创建一个文档片段,再把新创建的节点插入到文档片段中,再把该文档片段插入到文档树中。这样做的好处是可以减少页面的重新排列(reflow)。

每次对文档树的 DOM 操作都会导致页面重新排列,从而影响 Web 应用的性能。

有两种情况下的 DOM 操作不会导致页面重新排列:一种是对不可见元素(CSS 样式 display的值是

none)的操作,另外一种是不在当前文档树中的元素。由于文档片段不在当前文档树中,

对它的修改并不会造成页面的重新排列。

使用 innerHTML:这种做法是通过字符串拼接来构造 HTML 文档,再通过设置元素的 innerHTML来修改其内容。使用

innerHTML比一般的 DOM 操作要快。

使用 cloneNode():当需要创建多个结构相同的元素时,比较好的办法是首先创建出一个元素作为模板,然后用

cloneNode()方法复制出其它的元素。

这样比逐个创建每个元素速度要快。需要注意的是,通过

cloneNode()复制出来的元素会丢失原来绑定在其上的事件处理方法,需要重新进行事件绑定。

var df = document_createDocumentFragment();

for (var i = 0; i 

dojo.create("div", {

innerHTML : "node " + i

}, df);

}

var node = dojo.byId("myDiv");

for (var i = 0; i 

node.a(df.cloneNode(true));

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值