<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
jQuery - 创建DOM模型
</
title
>
<
script
src
="../Static/common/js/jquery-1.5.1.min.js"
type
="text/javascript"
></
script
>
</
head
>
<
body
>
<!--
页面内容部分
-->
<
div
id
="divMsg"
></
div
>
<
div
id
="divHolder"
></
div
>
<!--
尾部脚本块
-->
<
script
type
="text/javascript"
>
var
thisPage
=
{
initialize:
function
() {
//
加载时执行
this
.initializeDom();
this
.initializeEvent();
this
.createDom1();
this
.createDom2();
//
this.createDom3();
},
initializeDom:
function
() {
//
初始化DOM
this
.holder
=
document.getElementById(
"
divHolder
"
);
this
.divMsg
=
document.getElementById(
"
divMsg
"
);
},
initializeEvent:
function
() {
//
事件绑定
},
createDom1:
function
() {
var
startDate
=
new
Date();
var
builder
=
new
Array();
for
(
var
i
=
0
; i
<
100
; i
++
) {
builder.push(
"
<div style='width:100px; height:20px;background-color:#eee'>test</div>
"
);
};
this
.holder.innerHTML
=
builder.join(
""
);
this
.divMsg.innerHTML
+=
"
使用innerHTML耗时:
"
+
(
new
Date()
-
startDate);
},
createDom2:
function
() {
var
startDate
=
new
Date();
for
(
var
i
=
0
; i
<
100
; i
++
) {
var
oDiv
=
document.createElement(
"
div
"
);
var
oText
=
document.createTextNode(
"
text
"
);
oDiv.appendChild(oText);
this
.holder.appendChild(oDiv);
oDiv.style.width
=
"
100px
"
;
oDiv.style.height
=
"
20px
"
;
oDiv.style.backgroundColor
=
"
#eee
"
;
};
this
.divMsg.innerHTML
+=
"
<br/>使用createElement耗时:
"
+
(
new
Date()
-
startDate);
},
createDom3:
function
() {
var
startDate
=
new
Date();
jQuery(
"
<span/>
"
).attr(
"
id
"
,
"
mySpan
"
);
jQuery(
"
<span style='width:100px; height:20px;background-color:#eee'>test</span>
"
).appendTo(
this
.holder);
},
createDom4:
function
() {
jQuery(
"
<span>test</span><span>test</span><span>test</span><span>test</span>
"
).appendTo(
this
.holder);
}
}
$(thisPage.initialize());
</
script
>
</
body
>
</
html
>
jQuery(html,ownerDocument)函数用来创建DOM元素,并且以jQuery对象的形式返回:jQuery("<span/>").attr("id","mySpan");
即使用innerHtml的方式创建元素,在内部也会首先使用document.createElement创建一个div元素,然后调用div的innerHtml方法。