JS,Jquery,ExtJs不同脚本动态创建DOM对象

好久不来写东西了,这段时间太慢了,闲了下来看了几篇文章,觉得很好,同时也许咱们大家都能遇到,所以就把它记录下来...

简单使用JavaScript、JQuery、ExtJs进行DOM对象创建的测试,主要是使用JavaScript、JQuery、ExtJs动态创建Table对象、动态Table数据填充、多选控制。

1.简单前台数据处理
界面有点丑了,没美化界面,主要是JavaScript动态创建Table。效果图:
JS,Jquery,ExtJs不同脚本动态创建DOM对象

 <!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>Js创建Dom对象</title>
<script type="text/javascript" language="javascript"> function blurMessage() {
//输入姓名失去光标
var varName = document.getElementById("txtName");
var varMessgae = document.getElementById("txtMessage");
if (varName.value != null && varName.value.length <= ) {
alert("请输入姓名!");
return;
} varMessgae.innerHTML = varName.value + "说:";
varName.value = ""; //清空内容
} function showMessage() {
//显示提交的信息
var message = document.getElementById("txtMessage").value;
var date = new Date().toLocaleDateString();
var time = new Date().toLocaleTimeString();
if (!message) {
alert("请输入信息内容!");
return;
}
//获取显示表格对象
var tab = document.getElementById("tabMessage");
var tr = tab.insertRow();
var td1 = tr.insertCell(-);
td1.innerHTML = message;
var td2 = tr.insertCell(-);
td2.innerHTML = date;
var td3 = tr.insertCell(-);
td3.innerHTML = time; document.getElementById("txtMessage").value = '';
} </script>
</head>
<body>
<div id="divContain" style="width: 600px">
<div id="divMessage">
<table id="tabMessage" cellpadding="" cellspacing="" border="" style="width: 100%;
background-color: Yellow; border-width: 2px; border-bottom-width: 3px">
<tr>
<th>
留言信息
</th>
<th>
日期
</th>
<th>
时间
</th>
</tr>
</table>
</div>
<div id="divSubmitMessage">
<h3>
请填写你宝贵的建议:
</h3>
<div>
<input type="radio" id="rbNoName" onclick="txtName.style.display='none';txtMessage.innerHTML = '匿名说:';"
value="NoName" name="rbGroup" />匿名
<input type="radio" id="rbName" onclick="txtName.style.display=''" value="Name" name="rbGroup" />实名
<input type="text" id="txtName" style="display: none" onblur="blurMessage()" />
<br />
<textarea id="txtMessage" cols="" rows="" style="width: 100%"></textarea>
<br />
<input type="button" id="btnSubmit" onclick="showMessage()" style="float: right;
margin-top: 10px;" value="提交信息" />
</div>
</div>
</div>
</body>
</html>

个人觉得这个方式还可以再修改一下,这样的话是不是太繁琐了,况且JS的话使用的没有jquery的多,所以还是接着往下看看jquery的方法。

2.JavaScript动态创建DOM对象

使用JavaScript动态创建按钮、文本、链接、表格、加上CheckBox的表格(简单实现全选),这里Table的数据是页面数据,不是服务端数据,主要是与后面的JQuery和ExtJs请求服务端数据动态创建Table的差异比较。
界面有点丑,主要是看JavaScript动态创建Dom对象,效果图:

JS,Jquery,ExtJs不同脚本动态创建DOM对象

 <!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>
<style type="text/css">
.TestCss
{
color: Purple;
background-color: Silver;
}
</style>
<script type="text/javascript" language="javascript"> var count = ; //全局变量 //创建元素标签
function createElements() {
count++; //记录数累加 //创建input:button标签
var inputBtn = document.createElement("input");
inputBtn.setAttribute("type", "button");
inputBtn.setAttribute("value", "新建Button" + count);
inputBtn.setAttribute("class", "TestCss");
inputBtn.setAttribute("onclick", "alert(this.value)"); //创建input:text标签
var inputText = document.createElement("input");
inputText.setAttribute("type", "text");
inputText.setAttribute("value", "请输入文本");
inputText.setAttribute("style", "color:red;background-color:blue"); //创建iframe标签
var iframe = document.createElement("iframe");
iframe.width = "100%"
iframe.marginheight = "100px"
iframe.frameborder = "";
iframe.src = "Test.htm"; //Test.htm Test.doc //创建br标签
var br = document.createElement("br"); var divContent = document.getElementById("divContent");
divContent.appendChild(inputBtn); //将input:button标签追加divConent之后
divContent.appendChild(inputText); //将input:text标签追加divContent之后
//divContent.appendChild(iframe); //将iframe标签追加divContent之后
divContent.appendChild(br); //将br标签追加divContent之后
} //HTML拼接
function createLinks() {
count++; //创建A标签HTML文本
var idCount = "A" + count;
var valueCount = "新建连接" + count;
var link = "<a href='#' id='" + idCount + "' onclick='alert(this.id)'>" + valueCount + "</a>&nbsp;&nbsp;";
if (count % == ) {
link += "<br/>";
} var divContent = document.getElementById("divContent");
divContent.innerHTML += link; //divContent中累加HTML文本
} //根据行列创建table元素
function createTables(rowCount, colCount) {
count++;
//创建table标签
var tab = document.createElement("table");
tab.setAttribute("border", "");
tab.setAttribute("cellpadding", "");
tab.setAttribute("cellspacing", "");
//创建caption标签
var caption = document.createElement("caption");
caption.innerText = "表头信息" + count;
tab.appendChild(caption); //将caption追加table之后 for (var i = ; i <= rowCount; i++) {
var tr = document.createElement("tr");
for (var j = ; j <= colCount; j++) {
var td = document.createElement("td");
if (j % != ) {
var oddText = "第" + i + "行,第" + j + "列";
td.innerText = oddText; //奇数列内容
}
else {
var evenHtml = "<a href='#'>我是连接(" + i + "," + j + ")</a>";
td.innerHTML = evenHtml; //偶数列内容
}
tr.appendChild(td); //td追加到tr之后
}
if (i % == ) {//偶数行换色
tr.setAttribute("style", "background-color:orange");
}
tab.appendChild(tr); //tr追加到table之后
} var divContent = document.getElementById("divContent");
divContent.appendChild(tab); //table追加到divContent之后
} //根据数据创建Table
function createDataTable1() {
count++;
var data = [{ Name: "百度", Url: "www.baidu.com" }, { Name: "新浪", Url: "www.sina.com" }, { Name: "搜狐", Url: "www.sohu.com"}]; var tab = document.createElement("table");
tab.setAttribute("border", "");
tab.setAttribute("width", "260px");
tab.setAttribute("cellpadding", "");
tab.setAttribute("cellspacing", ""); var caption = document.createElement("caption");
caption.innerText = "数据信息" + count;
tab.appendChild(caption); for (var i = ; i < data.length; i++) {//遍历集合
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var dataHtml = "<a href='" + data[i].Url + "'>" + data[i].Name + "简介</a>";
td1.innerText = data[i].Name;
td2.innerHTML = dataHtml;
tr.appendChild(td1);
tr.appendChild(td2);
tab.appendChild(tr);
} var divContent = document.getElementById("divContent");
divContent.appendChild(tab);
} //根据数据创建Table并设置全选
function createDataTable2() {
count++;
var data = { "百度": "<a href='#'>百度简介</a>", "新浪": "<a href='#'>新浪简介</a>", "搜狐": "<a href='#'>搜狐简介</a>" }; var tab = document.createElement("table");
tab.setAttribute("border", "");
tab.setAttribute("width", "260px");
tab.setAttribute("cellpadding", "");
tab.setAttribute("cellspacing", ""); var caption = document.createElement("caption");
caption.innerText = "数据表头" + count;
tab.appendChild(caption); //添加列头
var chkAll = "<input type='checkbox' id='chkAll' name='chkAll' ></input>";
var th = document.createElement("tr");
var th0 = document.createElement("th");
var th1 = document.createElement("th");
var th2 = document.createElement("th");
th0.innerHTML = chkAll;
th1.innerText = "名称";
th2.innerText = "简介";
th.appendChild(th0);
th.appendChild(th1);
th.appendChild(th2);
tab.appendChild(th); //添加行数据
for (obj in data) {//遍历键
var tr = document.createElement("tr");
var td0 = document.createElement("td");
var td1 = document.createElement("td");
var td2 = document.createElement("td"); var chkSingle = "<input type='checkbox' name='chkSingle'></input>";
td0.innerHTML = chkSingle;
td1.innerText = obj; //取键的数据
td2.innerHTML = data[obj]; //取值的数据 tr.appendChild(td0);
tr.appendChild(td1);
tr.appendChild(td2);
tab.appendChild(tr);
} var divContent = document.getElementById("divContent");
divContent.appendChild(tab); //tab追加到divContent //全选设置
document.getElementById("chkAll").onclick = selectAll;
} function selectAll() {//全选设置
var chkAll = document.getElementById("chkAll");
var chkSingles = document.getElementsByName("chkSingle");
for (var i = ; i < chkSingles.length; i++) {
chkSingles[i].checked = chkAll.checked;
}
}
</script>
</head>
<body>
<div id="divContainer" style="background-color: Yellow; width: 600px; padding: 3px 5px 20px 3px;">
<input type="button" id="btnElement" value="创建元素" onclick="createElements()" />
<input type="button" id="btnText" value="添加链接" onclick="createLinks()" />
<input type="button" id="btnTable" value="添加行列表格" onclick="createTables(5,6)" />
<input type="button" id="btnDataTable" value="添加数据表格" onclick="createDataTable1();createDataTable2()" />
<div id="divContent" style="width: 100%; text-align: center">
</div>
</div>
</body>
</html>

3.JavaScript简单效果实现

自定义分割文本、Timer时钟使用、JS粘贴板使用、Div随鼠标移动的简单测试,这个稍稍好看些,效果图:

 <!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></title>
<style type="text/css">
.buttonCSS
{
border-style: outset;
border-color: Blue;
}
</style>
<script type="text/javascript" language="javascript"> var num = ; //计数器
var isStart = true; //时钟开关
var timerID = null; //时钟
//设置时钟
function setTimer() {
if (isStart) {
isStart = false;
timerID = setInterval("setCount()", ); //开启时钟
document.getElementById("btnTimer").value = "暂停时钟";
}
else {
isStart = true;
clearInterval(timerID); //暂停时钟
document.getElementById("btnTimer").value = "启动时钟";
}
}
function setCount() {
if (num > ) {
document.getElementById("divCount").innerText = num;
num--;
}
} //分割文本
function splitText() {
var textData = "李丽-女-23-测试";
var newText = "";
var tempData = textData; //用于处理文本
var index = tempData.indexOf('-');
while (index > ) {
newText += tempData.substring(, index) + "<br/>";
tempData = tempData.substring(index + , tempData.length);
index = tempData.indexOf('-');
} var divContent = document.getElementById("divContent");
divContent.innerHTML = "原是文本:<br/>" + textData;
divContent.innerHTML += "<br/>分割文本:<br/>" + newText;
divContent.innerHTML += "split方法分割:<br/>" + textData.split('-');
} //设置div位置
function flyDiv() {
var left = window.event.screenX - ;
var top = window.event.screenY - ;
//left = window.event.clientX;
//top = window.event.clientY;
var divFly = document.getElementById("divFly");
divFly.style.marginLeft = left + "px";
divFly.style.marginTop = top + "px";
} //写入数据
function copeData() {
var message = "分享与你!网站为:" + location.href + ";附带博客:http://www.cnblogs.com/SanMaoSpace/";
clipboardData.setData("Text", message);
alert("信息已复制到粘贴板,请粘贴!");
}
//读取数据
function pasteData() {
var text = clipboardData.getData("Text");
var textMessage = document.getElementById("textMessage");
textMessage.value = text;
} //全选控制
function selectAll(ckAll) {
var ckSingles = document.getElementsByName("ckSingle");
for (var i = ; i < ckSingles.length; i++) {
ckSingles[i].checked = ckAll.checked;
}
} //设置颜色
function setColor(obj) {
var thisColor = "green";
var othersColor = "yellow";
if (obj.type != "mousemove") {
thisColor = "yellow";
othersColor = "green"
} var tab = document.getElementById("tab");
for (var i = ; i < tab.rows.length; i++) {
if (tab.rows[i] == this) {
tab.rows[i].style.background = thisColor;
}
else {
tab.rows[i].style.background = othersColor;
}
}
} //根据颜色设置交替行颜色
function getColor(thisColor, othersColor) {
var tab = document.getElementById("tab");
tab.rows[].style.background = "highlight";
for (var i = ; i < tab.rows.length; i++) {
if (i % == ) {//交替换色
tab.rows[i].style.background = thisColor;
}
else {
tab.rows[i].style.background = othersColor;
}
}
}
function newColor(obj) {
var thisColor = "green";
var othersColor = "yellow";
if (obj.type != "mousemove") {
var temp = thisColor;
thisColor = othersColor;
othersColor = temp;
} getColor(thisColor, othersColor);
} function changeColor() {//改变颜色
var tab = document.getElementById("tab");
for (var i = ; i < tab.rows.length; i++) {
tab.rows[i].onmousemove = setColor; //newColor setColor
tab.rows[i].onmouseout = setColor; //newColor setColor
}
} </script>
</head>
<body onload="changeColor()">
<div id="divContainer" style="width: 500px; background-color: Orange; padding-left: 3px;
padding-top: 3px; padding-right: 10px; padding-bottom: 20px">
<div id="divTools">
<input type="button" id="btnText" class="buttonCSS" value="分割文本" onclick="splitText()" />
<input type="button" id="btnTimer" class="buttonCSS" value="开启时钟" onclick="setTimer()" />
<input type="button" id="btnSet" class="buttonCSS" value="分享网址" onclick="copeData()" />
<input type="button" id="btnGet" class="buttonCSS" value="粘贴网址" onclick="pasteData()" />
<input type="button" id="btnDiv" class="buttonCSS" value="飞翔DIV" onclick="document.onmousemove = flyDiv;" />
</div>
<div id="divTable">
<table id="tab" border="" cellpadding="" cellspacing="" style="border-color: Blue;
margin-top: 5px; border-style: double; border-width: 1px; width: %; height: 150px;
text-align: center">
<tr id="tr">
<th>
<input type="checkbox" id="ckAll" name="ckAll" onclick="selectAll(this)" />
</th>
<th>
编号
</th>
<th>
标题
</th>
<th>
内容
</th>
</tr>
<tr>
<td>
<input type="checkbox" name="ckSingle" />
</td>
<td> </td>
<td>
标题1
</td>
<td>
内容1
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ckSingle" />
</td>
<td> </td>
<td>
标题2
</td>
<td>
内容2
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ckSingle" />
</td>
<td> </td>
<td>
标题3
</td>
<td>
内容3
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="ckSingle" />
</td>
<td> </td>
<td>
标题4
</td>
<td>
内容4
</td>
</tr>
</table>
</div>
<div id="divContent" style="width: 100%; margin-top: 10px; background-color: Yellow;
padding: 5px 0px 0px 5px">
</div>
<div id="divCount" style="width: 100%; margin-top: 10px; background-color: Yellow;
padding: 5px 0px 0px 5px; font-size: 20px; text-align: center">
</div>
<div id="divText" style="width: 100%; margin-top: 10px;">
<textarea id="textMessage" rows="" cols="" style="width: 100%"></textarea>
</div>
</div>
<div id="divFly" style="width: 200px; height: 100px; background-color: Purple; text-align: center;
position: absolute; padding-top: 50px">
我是移动DIV!
</div>
</body>
</html>

4.使用XMLHttp进行Ajax调用动态创建Table

主要是使用XMLHttpRequest的AJAX请求服务端数据,服务端使用一般处理程序(*.ashx)处理,并使用JavaScriptSerializer和DataContractJsonSerializer进行对象的序列化操作,转换为JSON字符串数据发送客户端,客户端再进行反序列化操作,进行动态Table创建和数据填充。
注意:前端JQuery和ExtJs脚本的引入以及服务端两个序列化所在的命名空间(System.Web.Script.Serialization和System.Runtime.Serialization.Json)的引入。

 <script src="../../Scripts/ext-base.js" type="text/javascript"></script>
<script src="../../Scripts/ext-all.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
效果图:

JS,Jquery,ExtJs不同脚本动态创建DOM对象

前端代码:
 <head>
<title></title>
<style type="text/css">
.buttonCSS
{
border-style: outset;
border-color: Purple;
}
</style>
<script src="../../Scripts/ext-base.js" type="text/javascript"></script>
<script src="../../Scripts/ext-all.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var ajaxReq = null;
function ajaxData() {
var url = "../Ajaxs/AjaxHandler.ashx";
// url = "AjaxHandler.ashx?args=AA";
// url = "AjaxHandler.ashx?type=insert&data=AA";
// url = "AjaxHandler.ashx?type=update&data=AA";
// encodeURI("");//注意对汉字连接字符串的乱码
if (window.XMLHttpRequest) {
ajaxReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
ajaxReq = new ActiveXObject("Microsoft.XMLHttp");
}
catch (e) {
ajaxReq = new ActiveXObject("Msxml2.XMLHTTP");
}
} if (ajaxReq) {
ajaxReq.open("POST", url);
ajaxReq.onreadystatechange = readyStateChange;
ajaxReq.send(null);
}
} function readyStateChange() {
if (ajaxReq) {
if (ajaxReq.readyState == "") {//请求完成
if (ajaxReq.status == "") {//执行成功
var data = ajaxReq.responseText; //ajaxReq.responseXML
var jqueryData = $.parseJSON(data); //JQuery反序列化
var ExtJsData = Ext.util.JSON.decode(data); //ExtJs反序列化 $("#divContent").html("信息加载成功!"); //DOM创建Table
createDomTable(ExtJsData); //Html拼接JQuery创建Table
createJoinTable1(jqueryData); //Html拼接ExtJs创建Table
createJoinTable2(ExtJsData); //JQuery创建Table
createJQueryTable(jqueryData); //ExtJs创建Table
createExtJsTable(ExtJsData); //ExtJs的createTemplate创建Table
createExtJsTemplate(ExtJsData); //ExtJs的XTemplate创建Table
//这个方法会重写divContent的内容
//createExtJsXTemplate();
}
else {//执行失败
alert("服务器状态:" + ajaxReq.statusText);
}
}
else {
var message = "信息加载中......";
$("#divContent").html(message); //Jquery显示内容
//Ext.get("divContent").dom.innerHTML = message;//ExtJs显示内容
}
}
} //DOM创建Table
function createDomTable(data) {
var tab = document.createElement("table"); //创建tab对象
tab.setAttribute("border", ""); //设置table属性
tab.setAttribute("width", "200px");
tab.setAttribute("cellspacing", "");
tab.setAttribute("cellpadding", ""); var caption = document.createElement("caption"); //创建caption对象
caption.innerText = "DOM Create Table";
tab.appendChild(caption); //caption追加table for (var i = ; i < data.length; i++) {//遍历数据
var tr = document.createElement("tr"); //创建tr
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = data[i].Name;
td2.innerHTML = data[i].Html; tr.appendChild(td1);
tr.appendChild(td2);
tab.appendChild(tr);
} document.getElementById("divContent").appendChild(tab);
} //拼接Html标签JQuery创建Table
function createJoinTable1(data) {
var tabHtml = "<table id='tab1' width='200px' cellspacing='1' cellpadding='1' border='1'>";
tabHtml += "<caption>JQuery Join Table</caption>"; $(data).each(function (index, item) {
tabHtml += "<tr>";
tabHtml += "<td>" + item.Name + "</td>";
tabHtml += "<td>" + item.Html + "</td>";
tabHtml += "</tr>";
});
tabHtml += "</table>"; $("#divContent").append(tabHtml);
//$("#tab1").attr("cellspacing", "0").attr("cellpadding", "0"); //修改Table属性
} //拼接Html标签ExtJs创建Table
function createJoinTable2(data) {
var tabHtml = "<table id='tab2' width='200px' cellspacing='1' cellpadding='1' border='1'>";
tabHtml += "<caption>ExtJs Join Table</caption>"; Ext.each(data, function (item) {
tabHtml += "<tr>";
tabHtml += "<td>" + item.Name + "</td>";
tabHtml += "<td>" + item.Html + "</td>";
tabHtml += "</tr>";
});
tabHtml += "</table>"; Ext.get("divContent").dom.innerHTML += tabHtml;
//Ext.get("tab2").dom.cellSpacing = 0;//修改属性cellSpacing
//Ext.get("tab2").dom.cellPadding = 0;//修改属性cellPadding
} //JQuery创建Table
function createJQueryTable(data) {
//创建table对象
var tab = $("<table/>", { width: "200px", cellspacing: "", cellpadding: "", border: "" });
$("<caption/>").text("JQuery Create Table").appendTo(tab); //创建caption并追加到tab
$(data).each(function (index, item) {//遍历数据
var tr = $("<tr/>").appendTo(tab); //创建tr并追加到tab
$("<td/>").html(item.Name).appendTo(tr); //创建td并追加到tr
$("<td/>").html(item.Html).appendTo(tr);
}); tab.appendTo($("#divContent")); //tab追加到divContent
//$("#divContent").append(tab);//divContent后追加tab
} //ExtJs创建Table
function createExtJsTable(data) {
var divContent = Ext.get("divContent");
var tabTag = { tag: 'table', children: [{ tag: 'caption', html: 'ExtJs Create Table'}], style: 'width:200px;border: 1px solid blue;' };
var tab = Ext.DomHelper.append(divContent, tabTag); //将table追加到divContent Ext.each(data, function (item) {
var trTag = { tag: 'tr', children: [
{ tag: 'td', html: item.Name, style: "border: 1px solid blue;" },
{ tag: 'td', html: item.Html, style: "border: 1px solid blue;" }
]
};
Ext.DomHelper.append(tab, trTag); //将tr追加到table
}); //也可以使用createHtml方法
//var tab = Ext.DomHelper.createHtml(tabTag);
//Ext.DomHelper.append(divContent, tab);
} //使用ExtJs的createTemplate创建Table
function createExtJsTemplate(data) {
var divContent = Ext.get("divContent");
var tabTag = { id: 'MyTab', tag: 'table', children: [{ tag: 'caption', html: 'ExtJs Template Table'}],
style: 'width:200px; border: 1px solid blue;'
};
var tab = Ext.DomHelper.append(divContent, tabTag); //创建模版
var tpl = Ext.DomHelper.createTemplate({ tag: 'tr', children: [
{ tag: 'td', html: "{0}", style: "border: 1px solid blue;" },
{ tag: 'td', html: "{1}", style: "border: 1px solid blue;" }
]
});
Ext.each(data, function (item) {
tpl.append(tab, [item.Name, item.Html]); //筛入数据
});
} //使用ExtJs的XTemplate创建Table
function createExtJsXTemplate() {
var data = { Messages: [{ Name: "百度", Html: "<a href='#'>百度简介</a>" },
{ Name: "新浪", Html: "<a href='#'>新浪简介</a>" },
{ Name: "搜狐", Html: "<a href='#'>搜狐简介</a>"}]
}; var divContent = Ext.get("divContent");
var tpl = new Ext.XTemplate(//创建模版
'<table width="200px" cellspacing="1" cellpadding="1" border="1">',
'<caption>ExtJs XTemplate Table</caption>',
'<tpl for="Messages">',
'<tr><td>{Name}</td><td>{Html}</td></tr>',
'</tpl>',
'</table>'
);
tpl.compile(); //模版编译一下
tpl.overwrite(divContent, data); //模版重写
}
</script>
</head>
<body>
<div id="divContainer" style="width: 500px; background-color: Teal; padding: 5px 10px 20px 5px">
<div id="divTools">
<input type="button" id="btnAjaxTable" class="buttonCSS" value="添加Ajax表格" onclick="ajaxData()" />
<input type="button" id="btnSelAll" class="buttonCSS" value="添加全选表格" onclick="JQueryAjax();ExtJsAjax()" />
<input type="button" id="btnCreateObjs" class="buttonCSS" value="创建其他对象" onclick="createJQueryObjs();createExtJsObjs()" />
</div>
<div id="divContent" style="width: 100%; background-color: Yellow; padding-top: 3px;
padding-left: 5px; padding-bottom: 10px; text-align: center">
</div>
</div>
</body>
</html>

服务端代码:

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using System.Web.Script.Serialization; namespace JsJQueryExtJsReview.JQueryReview.Ajaxs
{
/// <summary>
/// AjaxHandler 的摘要说明
/// </summary>
public class AjaxHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";//application/json text/plain
string JsonData = string.Empty; System.Threading.Thread.Sleep();//延迟2000毫秒 List<Message> list = initMessages(); JsonData = GetJavaScriptData(list);//JavaScript序列化操作
JsonData = GetDataContractData(list);//DataContract序列化操作 context.Response.Write(JsonData);
} /// <summary>
/// DataContractJsonSerializer序列化数据
/// </summary>
/// <param name="messages">信息对象集合</param>
/// <returns>信息对象Json串</returns>
private string GetDataContractData(List<Message> messages)
{
string json = string.Empty;
DataContractJsonSerializer dataContract = new DataContractJsonSerializer(messages.GetType());
MemoryStream ms = new MemoryStream();
dataContract.WriteObject(ms, messages);
json = Encoding.UTF8.GetString(ms.ToArray());
return json;
} /// <summary>
/// JavaScriptSerializer序列化数据
/// </summary>
/// <param name="messages">信息对象集合</param>
/// <returns>信息对象Json串</returns>
private string GetJavaScriptData(List<Message> messages)
{
string json = string.Empty;
JavaScriptSerializer javaScript = new JavaScriptSerializer();
json = javaScript.Serialize(messages);
return json;
} /// <summary>
/// 初始化数据
/// </summary>
/// <returns></returns>
private List<Message> initMessages()
{
List<Message> list = new List<Message>() {
new Message(){ Name="百度",Html="<a href='#'>百度简介</a>"},
new Message(){ Name="新浪",Html="<a href='#'>新浪简介</a>"},
new Message(){ Name="搜狐",Html="<a href='#'>搜狐简介</a>"}
}; return list;
} public bool IsReusable
{
get
{
return false;
}
}
} public class Message
{
public string Name { get; set; }
public string Html { get; set; }
}
}

5.使用JQuery和ExtJs进行Ajax调用动态创建Table

主要是对JQuery、ExtJs的Ajax使用以及如何使用JQuery、ExtJs动态创建Table对象填充数据,简单实现CheckBox的全选操作。服务端的代码是第4点的一般处理程序。效果图:
JS,Jquery,ExtJs不同脚本动态创建DOM对象
代码如下:

 //JQuery的Ajax方式取得数据,添加全选按钮
function JQueryAjax() {
var message = "JQuery信息加载中......";
var divMessage = "<div style='color:green;'>" + message + "</div>";
$("#divContent").html(divMessage); $.ajax({
type: "POST",
url: "../Ajaxs/AjaxHandler.ashx",
async: true, //异步加载信息
dataType: "json",
success: function (data) {
var message = "JQuery信息加载成功!";
var divMessage = "<div style='color:green;'>" + message + "</div>";
$("#divContent").html(divMessage); createJQueryTable(data);
JQueryCHKBoxTable(data);
},
error: function () { alert("请求失败!"); }
});
} function JQueryCHKBoxTable(data) {
var tab = $("<table/>", { width: "300px", cellSpacing: "", cellPadding: "", border: "" });
$("<caption/>").text("JQuery CheckBox Table").appendTo(tab); var ths = $("<tr/>").appendTo(tab);
var th0 = $("<th/>").appendTo(ths);
$("<input/>", { type: "checkbox", id: "chAll" }).appendTo(th0);
$("<th/>", { text: "名称" }).appendTo(ths);
$("<th/>", { text: "简介" }).appendTo(ths); $(data).each(function (index, item) {
var tr = $("<tr/>").appendTo(tab);
var td0 = $("<td/>").appendTo(tr);
$("<input>", { type: "checkbox", name: "chSingle" }).appendTo(td0);
$("<td/>").html(item.Name).appendTo(tr);
$("<td/>").html(item.Html).appendTo(tr);
}); tab.appendTo($("#divContent")); $("#chAll").click(function (obj) {
var chSingles = $("input:[name='chSingle']");
$(chSingles).each(function (index, item) {
item.checked = $("#chAll")[].checked; //$("#chAll"),查询出来的是一个集合
});
}); // $("#chAll")[0].onclick = function () {//$("#chAll"),查询出来的是一个集合
// var chSingles = $("input:[name='chSingle']");
// $(chSingles).each(function (index, item) {
// item.checked = $("#chAll")[0].checked;
// });
// }
} //ExtJs的Ajax方式取得数据,添加全选按钮
function ExtJsAjax() {
var message = "ExtJs信息加载中......";
var divMessage = "<div id='divMessage' style='color:green;'>" + message + "</div>";
var divContent = Ext.get("divContent");
Ext.DomHelper.append(divContent, divMessage); Ext.Ajax.request({
method: "POST",
url: "../Ajaxs/AjaxHandler.ashx",
async: true, //异步加载信息
success: function (response, opts) {
message = "ExtJs信息加载成功!";
var divMessage = "<div style='color:green;'>" + message + "</div>";
//Ext.get("divMessage").dom.innerHTML = message;
Ext.DomHelper.append(divContent, divMessage); var data = Ext.util.JSON.decode(response.responseText);
createExtJsTable(data); //ExtJs创建Table
ExtJsCHKBoxTable(data); //ExtJs创建CheckBox的Table
},
failure: function (response, opts) { alert("请求失败!"); }
});
} //ExtJs的CheckBox Table
function ExtJsCHKBoxTable(data) {
var divContent = Ext.get("divContent");
var tabTag = { tag: "table", style: "width:300px;border:1px solid blue", children: [{ tag: "caption", html: "ExtJs CheckBox Table"}] };
var tab = Ext.DomHelper.append(divContent, tabTag); //将table追加到divContent //创建列头
var ths = { tag: "tr", children: [
{ tag: "th", style: "border:1px solid blue", children: [
{ tag: "input", type: "checkbox", id: "chkAll" }
]
},
{ tag: "th", style: "border:1px solid blue", html: "名称" },
{ tag: "th", style: "border:1px solid blue", html: "简介" }
]
};
Ext.DomHelper.append(tab, ths); //将tr追加到table Ext.each(data, function (item) {//遍历数据
var trTag = { tag: "tr", children: [
{ tag: "td", style: "border:1px solid blue", children: [{ tag: "input", type: "checkbox", name: "chkSingle"}] },
{ tag: "td", style: "border:1px solid blue", html: item.Name },
{ tag: "td", style: "border:1px solid blue", html: item.Html }
]
};
Ext.DomHelper.append(tab, trTag); //将tr追加到table
}); Ext.get("chkAll").on("change", function (obj) {
var chkSingles = Ext.query("input[name='chkSingle']"); //Dom集合
Ext.each(chkSingles, function (item) {
item.checked = Ext.get("chkAll").dom.checked;
});
}); // Ext.get("chkAll").addListener("click", function (obj) {
// var chkSingles = Ext.query("input[name='chkSingle']"); //Dom集合
// Ext.each(chkSingles, function (item) {
// item.checked = Ext.get("chkAll").dom.checked;
// });
// });
}

6.使用JQuery和ExtJs简单创建对象

其实前面复杂的操作处理了,这个就比较简单,简单创建几个input对象。依然是第4点的页面,再加上下面2个脚本函数,代码如下

 //JQuery创建其他对象
function createJQueryObjs() {
var divContent = $("#divContent").css("text-align", "left").append("<div>JQuery创建其他对象</div>"); $("<input/>", { type: "button", val: "创建按钮" }).appendTo(divContent);
$("<br/>").appendTo(divContent);
$("<input/>", { type: "button", val: "添加样式", class: "buttonCSS" }).appendTo(divContent);
$("<br/>").appendTo(divContent);
$("<input/>", { type: "button", val: "添加事件", click: function () {
alert($(this).val() + ",测试成功!");
}
}).appendTo(divContent);
$("<br/>").appendTo(divContent);
$("<input/>", { type: "text", id: "txt", val: '创建文本', css: { "background-color": "red"} }).appendTo(divContent);
$("<br/>").appendTo(divContent);
$("<input/>", { type: "radio", name: "sex", val: "男" }).appendTo(divContent);
$("<label/>", { text: "男" }).appendTo(divContent);
$("<input/>", { type: "radio", name: "sex", val: "女", checked: "true" }).appendTo(divContent);
$("<label/>", { text: "女" }).appendTo(divContent);
$("<br/>").appendTo(divContent);
} //ExtJs创建其他对象
function createExtJsObjs() {
var divContent = Ext.get("divContent");
Ext.DomHelper.append(divContent, "<hr/>ExtJs创建其他对象<br/>");
var buttonTag = { tag: "input", type: "button", value: "ExtJs按钮" };
Ext.DomHelper.append(divContent, buttonTag);
Ext.DomHelper.append(divContent, "<br/>");
var textTag = { tag: "input", type: "text", id: "testText", value: "ExtJs文本框" };
Ext.DomHelper.append(divContent, textTag);
}

使用原生JavaScript动态创建Table有些生硬,不太灵活;使用JQuery和ExtJs是各个API方法的调用,相对灵活些,代码也相对减小一些。
ExtJs一般不用Table来显示列表数据,一般直接用GridPanel直接绑定数据,显示数据,再加上CheckBox的多选功能。

先记下来吧,等有空了,把它整理一下。

上一篇:PHP中访问控制修饰符


下一篇:XML是什么东西