JS,Jquery,ExtJs不同脚本动态创建DOM对象
好久不来写东西了,这段时间太慢了,闲了下来看了几篇文章,觉得很好,同时也许咱们大家都能遇到,所以就把它记录下来...
简单使用JavaScript、JQuery、ExtJs进行DOM对象创建的测试,主要是使用JavaScript、JQuery、ExtJs动态创建Table对象、动态Table数据填充、多选控制。
1.简单前台数据处理
界面有点丑了,没美化界面,主要是JavaScript动态创建Table。效果图:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>Js创建Dom对象</title> 5 <script type="text/javascript" language="javascript"> 6 7 function blurMessage() { 8 //输入姓名失去光标 9 var varName = document.getElementById("txtName"); 10 var varMessgae = document.getElementById("txtMessage"); 11 if (varName.value != null && varName.value.length <= 0) { 12 alert("请输入姓名!"); 13 return; 14 } 15 16 varMessgae.innerHTML = varName.value + "说:"; 17 varName.value = ""; //清空内容 18 } 19 20 function showMessage() { 21 //显示提交的信息 22 var message = document.getElementById("txtMessage").value; 23 var date = new Date().toLocaleDateString(); 24 var time = new Date().toLocaleTimeString(); 25 if (!message) { 26 alert("请输入信息内容!"); 27 return; 28 } 29 //获取显示表格对象 30 var tab = document.getElementById("tabMessage"); 31 var tr = tab.insertRow(1); 32 var td1 = tr.insertCell(-1); 33 td1.innerHTML = message; 34 var td2 = tr.insertCell(-1); 35 td2.innerHTML = date; 36 var td3 = tr.insertCell(-1); 37 td3.innerHTML = time; 38 39 document.getElementById("txtMessage").value = ''; 40 } 41 42 </script> 43 </head> 44 <body> 45 <div id="divContain" style="width: 600px"> 46 <div id="divMessage"> 47 <table id="tabMessage" cellpadding="0" cellspacing="0" border="1" style="width: 100%; 48 background-color: Yellow; border-width: 2px; border-bottom-width: 3px"> 49 <tr> 50 <th> 51 留言信息 52 </th> 53 <th> 54 日期 55 </th> 56 <th> 57 时间 58 </th> 59 </tr> 60 </table> 61 </div> 62 <div id="divSubmitMessage"> 63 <h3> 64 请填写你宝贵的建议: 65 </h3> 66 <div> 67 <input type="radio" id="rbNoName" onclick="txtName.style.display='none';txtMessage.innerHTML = '匿名说:';" 68 value="NoName" name="rbGroup" />匿名 69 <input type="radio" id="rbName" onclick="txtName.style.display=''" value="Name" name="rbGroup" />实名 70 <input type="text" id="txtName" style="display: none" onblur="blurMessage()" /> 71 <br /> 72 <textarea id="txtMessage" cols="110" rows="5" style="width: 100%"></textarea> 73 <br /> 74 <input type="button" id="btnSubmit" onclick="showMessage()" style="float: right; 75 margin-top: 10px;" value="提交信息" /> 76 </div> 77 </div> 78 </div> 79 </body> 80 </html>
个人觉得这个方式还可以再修改一下,这样的话是不是太繁琐了,况且JS的话使用的没有jquery的多,所以还是接着往下看看jquery的方法。
2.JavaScript动态创建DOM对象
使用JavaScript动态创建按钮、文本、链接、表格、加上CheckBox的表格(简单实现全选),这里Table的数据是页面数据,不是服务端数据,主要是与后面的JQuery和ExtJs请求服务端数据动态创建Table的差异比较。
界面有点丑,主要是看JavaScript动态创建Dom对象,效果图:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title>Jquery创建DOM对象</title> 5 <style type="text/css"> 6 .TestCss 7 { 8 color: Purple; 9 background-color: Silver; 10 } 11 </style> 12 <script type="text/javascript" language="javascript"> 13 14 var count = 0; //全局变量 15 16 //创建元素标签 17 function createElements() { 18 count++; //记录数累加 19 20 //创建input:button标签 21 var inputBtn = document.createElement("input"); 22 inputBtn.setAttribute("type", "button"); 23 inputBtn.setAttribute("value", "新建Button" + count); 24 inputBtn.setAttribute("class", "TestCss"); 25 inputBtn.setAttribute("onclick", "alert(this.value)"); 26 27 //创建input:text标签 28 var inputText = document.createElement("input"); 29 inputText.setAttribute("type", "text"); 30 inputText.setAttribute("value", "请输入文本"); 31 inputText.setAttribute("style", "color:red;background-color:blue"); 32 33 //创建iframe标签 34 var iframe = document.createElement("iframe"); 35 iframe.width = "100%" 36 iframe.marginheight = "100px" 37 iframe.frameborder = "0"; 38 iframe.src = "Test.htm"; //Test.htm Test.doc 39 40 //创建br标签 41 var br = document.createElement("br"); 42 43 var divContent = document.getElementById("divContent"); 44 divContent.appendChild(inputBtn); //将input:button标签追加divConent之后 45 divContent.appendChild(inputText); //将input:text标签追加divContent之后 46 //divContent.appendChild(iframe); //将iframe标签追加divContent之后 47 divContent.appendChild(br); //将br标签追加divContent之后 48 } 49 50 //HTML拼接 51 function createLinks() { 52 count++; 53 54 //创建A标签HTML文本 55 var idCount = "A" + count; 56 var valueCount = "新建连接" + count; 57 var link = "<a href='#' id='" + idCount + "' onclick='alert(this.id)'>" + valueCount + "</a> "; 58 if (count % 2 == 0) { 59 link += "<br/>"; 60 } 61 62 var divContent = document.getElementById("divContent"); 63 divContent.innerHTML += link; //divContent中累加HTML文本 64 } 65 66 //根据行列创建table元素 67 function createTables(rowCount, colCount) { 68 count++; 69 //创建table标签 70 var tab = document.createElement("table"); 71 tab.setAttribute("border", "1"); 72 tab.setAttribute("cellpadding", "0"); 73 tab.setAttribute("cellspacing", "0"); 74 //创建caption标签 75 var caption = document.createElement("caption"); 76 caption.innerText = "表头信息" + count; 77 tab.appendChild(caption); //将caption追加table之后 78 79 for (var i = 1; i <= rowCount; i++) { 80 var tr = document.createElement("tr"); 81 for (var j = 1; j <= colCount; j++) { 82 var td = document.createElement("td"); 83 if (j % 2 != 0) { 84 var oddText = "第" + i + "行,第" + j + "列"; 85 td.innerText = oddText; //奇数列内容 86 } 87 else { 88 var evenHtml = "<a href='#'>我是连接(" + i + "," + j + ")</a>"; 89 td.innerHTML = evenHtml; //偶数列内容 90 } 91 tr.appendChild(td); //td追加到tr之后 92 } 93 if (i % 2 == 0) {//偶数行换色 94 tr.setAttribute("style", "background-color:orange"); 95 } 96 tab.appendChild(tr); //tr追加到table之后 97 } 98 99 var divContent = document.getElementById("divContent"); 100 divContent.appendChild(tab); //table追加到divContent之后 101 } 102 103 //根据数据创建Table 104 function createDataTable1() { 105 count++; 106 var data = [{ Name: "百度", Url: "www.baidu.com" }, { Name: "新浪", Url: "www.sina.com" }, { Name: "搜狐", Url: "www.sohu.com"}]; 107 108 var tab = document.createElement("table"); 109 tab.setAttribute("border", "1"); 110 tab.setAttribute("width", "260px"); 111 tab.setAttribute("cellpadding", "1"); 112 tab.setAttribute("cellspacing", "1"); 113 114 var caption = document.createElement("caption"); 115 caption.innerText = "数据信息" + count; 116 tab.appendChild(caption); 117 118 for (var i = 0; i < data.length; i++) {//遍历集合 119 var tr = document.createElement("tr"); 120 var td1 = document.createElement("td"); 121 var td2 = document.createElement("td"); 122 var dataHtml = "<a href='" + data[i].Url + "'>" + data[i].Name + "简介</a>"; 123 td1.innerText = data[i].Name; 124 td2.innerHTML = dataHtml; 125 tr.appendChild(td1); 126 tr.appendChild(td2); 127 tab.appendChild(tr); 128 } 129 130 var divContent = document.getElementById("divContent"); 131 divContent.appendChild(tab); 132 } 133 134 //根据数据创建Table并设置全选 135 function createDataTable2() { 136 count++; 137 var data = { "百度": "<a href='#'>百度简介</a>", "新浪": "<a href='#'>新浪简介</a>", "搜狐": "<a href='#'>搜狐简介</a>" }; 138 139 var tab = document.createElement("table"); 140 tab.setAttribute("border", "1"); 141 tab.setAttribute("width", "260px"); 142 tab.setAttribute("cellpadding", "1"); 143 tab.setAttribute("cellspacing", "1"); 144 145 var caption = document.createElement("caption"); 146 caption.innerText = "数据表头" + count; 147 tab.appendChild(caption); 148 149 //添加列头 150 var chkAll = "<input type='checkbox' id='chkAll' name='chkAll' ></input>"; 151 var th = document.createElement("tr"); 152 var th0 = document.createElement("th"); 153 var th1 = document.createElement("th"); 154 var th2 = document.createElement("th"); 155 th0.innerHTML = chkAll; 156 th1.innerText = "名称"; 157 th2.innerText = "简介"; 158 th.appendChild(th0); 159 th.appendChild(th1); 160 th.appendChild(th2); 161 tab.appendChild(th); 162 163 //添加行数据 164 for (obj in data) {//遍历键 165 var tr = document.createElement("tr"); 166 var td0 = document.createElement("td"); 167 var td1 = document.createElement("td"); 168 var td2 = document.createElement("td"); 169 170 var chkSingle = "<input type='checkbox' name='chkSingle'></input>"; 171 td0.innerHTML = chkSingle; 172 td1.innerText = obj; //取键的数据 173 td2.innerHTML = data[obj]; //取值的数据 174 175 tr.appendChild(td0); 176 tr.appendChild(td1); 177 tr.appendChild(td2); 178 tab.appendChild(tr); 179 } 180 181 var divContent = document.getElementById("divContent"); 182 divContent.appendChild(tab); //tab追加到divContent 183 184 //全选设置 185 document.getElementById("chkAll").onclick = selectAll; 186 } 187 188 function selectAll() {//全选设置 189 var chkAll = document.getElementById("chkAll"); 190 var chkSingles = document.getElementsByName("chkSingle"); 191 for (var i = 0; i < chkSingles.length; i++) { 192 chkSingles[i].checked = chkAll.checked; 193 } 194 } 195 </script> 196 </head> 197 <body> 198 <div id="divContainer" style="background-color: Yellow; width: 600px; padding: 3px 5px 20px 3px;"> 199 <input type="button" id="btnElement" value="创建元素" onclick="createElements()" /> 200 <input type="button" id="btnText" value="添加链接" onclick="createLinks()" /> 201 <input type="button" id="btnTable" value="添加行列表格" onclick="createTables(5,6)" /> 202 <input type="button" id="btnDataTable" value="添加数据表格" onclick="createDataTable1();createDataTable2()" /> 203 <div id="divContent" style="width: 100%; text-align: center"> 204 </div> 205 </div> 206 </body> 207 </html>
3.JavaScript简单效果实现
自定义分割文本、Timer时钟使用、JS粘贴板使用、Div随鼠标移动的简单测试,这个稍稍好看些,效果图:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 <style type="text/css"> 6 .buttonCSS 7 { 8 border-style: outset; 9 border-color: Blue; 10 } 11 </style> 12 <script type="text/javascript" language="javascript"> 13 14 var num = 50000; //计数器 15 var isStart = true; //时钟开关 16 var timerID = null; //时钟 17 //设置时钟 18 function setTimer() { 19 if (isStart) { 20 isStart = false; 21 timerID = setInterval("setCount()", 10); //开启时钟 22 document.getElementById("btnTimer").value = "暂停时钟"; 23 } 24 else { 25 isStart = true; 26 clearInterval(timerID); //暂停时钟 27 document.getElementById("btnTimer").value = "启动时钟"; 28 } 29 } 30 function setCount() { 31 if (num > 0) { 32 document.getElementById("divCount").innerText = num; 33 num--; 34 } 35 } 36 37 //分割文本 38 function splitText() { 39 var textData = "李丽-女-23-测试"; 40 var newText = ""; 41 var tempData = textData; //用于处理文本 42 var index = tempData.indexOf('-'); 43 while (index > 0) { 44 newText += tempData.substring(0, index) + "<br/>"; 45 tempData = tempData.substring(index + 1, tempData.length); 46 index = tempData.indexOf('-'); 47 } 48 49 var divContent = document.getElementById("divContent"); 50 divContent.innerHTML = "原是文本:<br/>" + textData; 51 divContent.innerHTML += "<br/>分割文本:<br/>" + newText; 52 divContent.innerHTML += "split方法分割:<br/>" + textData.split('-'); 53 } 54 55 //设置div位置 56 function flyDiv() { 57 var left = window.event.screenX - 10; 58 var top = window.event.screenY - 400; 59 //left = window.event.clientX; 60 //top = window.event.clientY; 61 var divFly = document.getElementById("divFly"); 62 divFly.style.marginLeft = left + "px"; 63 divFly.style.marginTop = top + "px"; 64 } 65 66 //写入数据 67 function copeData() { 68 var message = "分享与你!网站为:" + location.href + ";附带博客:http://www.cnblogs.com/SanMaoSpace/"; 69 clipboardData.setData("Text", message); 70 alert("信息已复制到粘贴板,请粘贴!"); 71 } 72 //读取数据 73 function pasteData() { 74 var text = clipboardData.getData("Text"); 75 var textMessage = document.getElementById("textMessage"); 76 textMessage.value = text; 77 } 78 79 //全选控制 80 function selectAll(ckAll) { 81 var ckSingles = document.getElementsByName("ckSingle"); 82 for (var i = 0; i < ckSingles.length; i++) { 83 ckSingles[i].checked = ckAll.checked; 84 } 85 } 86 87 //设置颜色 88 function setColor(obj) { 89 var thisColor = "green"; 90 var othersColor = "yellow"; 91 if (obj.type != "mousemove") { 92 thisColor = "yellow"; 93 othersColor = "green" 94 } 95 96 var tab = document.getElementById("tab"); 97 for (var i = 0; i < tab.rows.length; i++) { 98 if (tab.rows[i] == this) { 99 tab.rows[i].style.background = thisColor; 100 } 101 else { 102 tab.rows[i].style.background = othersColor; 103 } 104 } 105 } 106 107 //根据颜色设置交替行颜色 108 function getColor(thisColor, othersColor) { 109 var tab = document.getElementById("tab"); 110 tab.rows[0].style.background = "highlight"; 111 for (var i = 1; i < tab.rows.length; i++) { 112 if (i % 2 == 0) {//交替换色 113 tab.rows[i].style.background = thisColor; 114 } 115 else { 116 tab.rows[i].style.background = othersColor; 117 } 118 } 119 } 120 function newColor(obj) { 121 var thisColor = "green"; 122 var othersColor = "yellow"; 123 if (obj.type != "mousemove") { 124 var temp = thisColor; 125 thisColor = othersColor; 126 othersColor = temp; 127 } 128 129 getColor(thisColor, othersColor); 130 } 131 132 function changeColor() {//改变颜色 133 var tab = document.getElementById("tab"); 134 for (var i = 0; i < tab.rows.length; i++) { 135 tab.rows[i].onmousemove = setColor; //newColor setColor 136 tab.rows[i].onmouseout = setColor; //newColor setColor 137 } 138 } 139 140 </script> 141 </head> 142 <body onload="changeColor()"> 143 <div id="divContainer" style="width: 500px; background-color: Orange; padding-left: 3px; 144 padding-top: 3px; padding-right: 10px; padding-bottom: 20px"> 145 <div id="divTools"> 146 <input type="button" id="btnText" class="buttonCSS" value="分割文本" onclick="splitText()" /> 147 <input type="button" id="btnTimer" class="buttonCSS" value="开启时钟" onclick="setTimer()" /> 148 <input type="button" id="btnSet" class="buttonCSS" value="分享网址" onclick="copeData()" /> 149 <input type="button" id="btnGet" class="buttonCSS" value="粘贴网址" onclick="pasteData()" /> 150 <input type="button" id="btnDiv" class="buttonCSS" value="飞翔DIV" onclick="document.onmousemove = flyDiv;" /> 151 </div> 152 <div id="divTable"> 153 <table id="tab" border="1" cellpadding="0" cellspacing="0" style="border-color: Blue; 154 margin-top: 5px; border-style: double; border-width: 1px; width: 100%; height: 150px; 155 text-align: center"> 156 <tr id="tr"> 157 <th> 158 <input type="checkbox" id="ckAll" name="ckAll" onclick="selectAll(this)" /> 159 </th> 160 <th> 161 编号 162 </th> 163 <th> 164 标题 165 </th> 166 <th> 167 内容 168 </th> 169 </tr> 170 <tr> 171 <td> 172 <input type="checkbox" name="ckSingle" /> 173 </td> 174 <td> 175 001 176 </td> 177 <td> 178 标题1 179 </td> 180 <td> 181 内容1 182 </td> 183 </tr> 184 <tr> 185 <td> 186 <input type="checkbox" name="ckSingle" /> 187 </td> 188 <td> 189 002 190 </td> 191 <td> 192 标题2 193 </td> 194 <td> 195 内容2 196 </td> 197 </tr> 198 <tr> 199 <td> 200 <input type="checkbox" name="ckSingle" /> 201 </td> 202 <td> 203 003 204 </td> 205 <td> 206 标题3 207 </td> 208 <td> 209 内容3 210 </td> 211 </tr> 212 <tr> 213 <td> 214 <input type="checkbox" name="ckSingle" /> 215 </td> 216 <td> 217 004 218 </td> 219 <td> 220 标题4 221 </td> 222 <td> 223 内容4 224 </td> 225 </tr> 226 </table> 227 </div> 228 <div id="divContent" style="width: 100%; margin-top: 10px; background-color: Yellow; 229 padding: 5px 0px 0px 5px"> 230 </div> 231 <div id="divCount" style="width: 100%; margin-top: 10px; background-color: Yellow; 232 padding: 5px 0px 0px 5px; font-size: 20px; text-align: center"> 233 </div> 234 <div id="divText" style="width: 100%; margin-top: 10px;"> 235 <textarea id="textMessage" rows="5" cols="3" style="width: 100%"></textarea> 236 </div> 237 </div> 238 <div id="divFly" style="width: 200px; height: 100px; background-color: Purple; text-align: center; 239 position: absolute; padding-top: 50px"> 240 我是移动DIV! 241 </div> 242 </body> 243 </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>
效果图:
前端代码:
1 <head> 2 <title></title> 3 <style type="text/css"> 4 .buttonCSS 5 { 6 border-style: outset; 7 border-color: Purple; 8 } 9 </style> 10 <script src="../../Scripts/ext-base.js" type="text/javascript"></script> 11 <script src="../../Scripts/ext-all.js" type="text/javascript"></script> 12 <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script> 13 <script type="text/javascript" language="javascript"> 14 var ajaxReq = null; 15 function ajaxData() { 16 var url = "../Ajaxs/AjaxHandler.ashx"; 17 // url = "AjaxHandler.ashx?args=AA"; 18 // url = "AjaxHandler.ashx?type=insert&data=AA"; 19 // url = "AjaxHandler.ashx?type=update&data=AA"; 20 // encodeURI("");//注意对汉字连接字符串的乱码 21 if (window.XMLHttpRequest) { 22 ajaxReq = new XMLHttpRequest(); 23 } 24 else if (window.ActiveXObject) { 25 try { 26 ajaxReq = new ActiveXObject("Microsoft.XMLHttp"); 27 } 28 catch (e) { 29 ajaxReq = new ActiveXObject("Msxml2.XMLHTTP"); 30 } 31 } 32 33 if (ajaxReq) { 34 ajaxReq.open("POST", url); 35 ajaxReq.onreadystatechange = readyStateChange; 36 ajaxReq.send(null); 37 } 38 } 39 40 function readyStateChange() { 41 if (ajaxReq) { 42 if (ajaxReq.readyState == "4") {//请求完成 43 if (ajaxReq.status == "200") {//执行成功 44 var data = ajaxReq.responseText; //ajaxReq.responseXML 45 var jqueryData = $.parseJSON(data); //JQuery反序列化 46 var ExtJsData = Ext.util.JSON.decode(data); //ExtJs反序列化 47 48 $("#divContent").html("信息加载成功!"); 49 50 //DOM创建Table 51 createDomTable(ExtJsData); 52 53 //Html拼接JQuery创建Table 54 createJoinTable1(jqueryData); 55 56 //Html拼接ExtJs创建Table 57 createJoinTable2(ExtJsData); 58 59 //JQuery创建Table 60 createJQueryTable(jqueryData); 61 62 //ExtJs创建Table 63 createExtJsTable(ExtJsData); 64 65 //ExtJs的createTemplate创建Table 66 createExtJsTemplate(ExtJsData); 67 68 //ExtJs的XTemplate创建Table 69 //这个方法会重写divContent的内容 70 //createExtJsXTemplate(); 71 } 72 else {//执行失败 73 alert("服务器状态:" + ajaxReq.statusText); 74 } 75 } 76 else { 77 var message = "信息加载中......"; 78 $("#divContent").html(message); //Jquery显示内容 79 //Ext.get("divContent").dom.innerHTML = message;//ExtJs显示内容 80 } 81 } 82 } 83 84 //DOM创建Table 85 function createDomTable(data) { 86 var tab = document.createElement("table"); //创建tab对象 87 tab.setAttribute("border", "1"); //设置table属性 88 tab.setAttribute("width", "200px"); 89 tab.setAttribute("cellspacing", "1"); 90 tab.setAttribute("cellpadding", "1"); 91 92 var caption = document.createElement("caption"); //创建caption对象 93 caption.innerText = "DOM Create Table"; 94 tab.appendChild(caption); //caption追加table 95 96 for (var i = 0; i < data.length; i++) {//遍历数据 97 var tr = document.createElement("tr"); //创建tr 98 var td1 = document.createElement("td"); 99 var td2 = document.createElement("td"); 100 td1.innerHTML = data[i].Name; 101 td2.innerHTML = data[i].Html; 102 103 tr.appendChild(td1); 104 tr.appendChild(td2); 105 tab.appendChild(tr); 106 } 107 108 document.getElementById("divContent").appendChild(tab); 109 } 110 111 //拼接Html标签JQuery创建Table 112 function createJoinTable1(data) { 113 var tabHtml = "<table id='tab1' width='200px' cellspacing='1' cellpadding='1' border='1'>"; 114 tabHtml += "<caption>JQuery Join Table</caption>"; 115 116 $(data).each(function (index, item) { 117 tabHtml += "<tr>"; 118 tabHtml += "<td>" + item.Name + "</td>"; 119 tabHtml += "<td>" + item.Html + "</td>"; 120 tabHtml += "</tr>"; 121 }); 122 tabHtml += "</table>"; 123 124 $("#divContent").append(tabHtml); 125 //$("#tab1").attr("cellspacing", "0").attr("cellpadding", "0"); //修改Table属性 126 } 127 128 //拼接Html标签ExtJs创建Table 129 function createJoinTable2(data) { 130 var tabHtml = "<table id='tab2' width='200px' cellspacing='1' cellpadding='1' border='1'>"; 131 tabHtml += "<caption>ExtJs Join Table</caption>"; 132 133 Ext.each(data, function (item) { 134 tabHtml += "<tr>"; 135 tabHtml += "<td>" + item.Name + "</td>"; 136 tabHtml += "<td>" + item.Html + "</td>"; 137 tabHtml += "</tr>"; 138 }); 139 tabHtml += "</table>"; 140 141 Ext.get("divContent").dom.innerHTML += tabHtml; 142 //Ext.get("tab2").dom.cellSpacing = 0;//修改属性cellSpacing 143 //Ext.get("tab2").dom.cellPadding = 0;//修改属性cellPadding 144 } 145 146 //JQuery创建Table 147 function createJQueryTable(data) { 148 //创建table对象 149 var tab = $("<table/>", { width: "200px", cellspacing: "1", cellpadding: "1", border: "1" }); 150 $("<caption/>").text("JQuery Create Table").appendTo(tab); //创建caption并追加到tab 151 $(data).each(function (index, item) {//遍历数据 152 var tr = $("<tr/>").appendTo(tab); //创建tr并追加到tab 153 $("<td/>").html(item.Name).appendTo(tr); //创建td并追加到tr 154 $("<td/>").html(item.Html).appendTo(tr); 155 }); 156 157 tab.appendTo($("#divContent")); //tab追加到divContent 158 //$("#divContent").append(tab);//divContent后追加tab 159 } 160 161 //ExtJs创建Table 162 function createExtJsTable(data) { 163 var divContent = Ext.get("divContent"); 164 var tabTag = { tag: 'table', children: [{ tag: 'caption', html: 'ExtJs Create Table'}], style: 'width:200px;border: 1px solid blue;' }; 165 var tab = Ext.DomHelper.append(divContent, tabTag); //将table追加到divContent 166 167 Ext.each(data, function (item) { 168 var trTag = { tag: 'tr', children: [ 169 { tag: 'td', html: item.Name, style: "border: 1px solid blue;" }, 170 { tag: 'td', html: item.Html, style: "border: 1px solid blue;" } 171 ] 172 }; 173 Ext.DomHelper.append(tab, trTag); //将tr追加到table 174 }); 175 176 //也可以使用createHtml方法 177 //var tab = Ext.DomHelper.createHtml(tabTag); 178 //Ext.DomHelper.append(divContent, tab); 179 } 180 181 //使用ExtJs的createTemplate创建Table 182 function createExtJsTemplate(data) { 183 var divContent = Ext.get("divContent"); 184 var tabTag = { id: 'MyTab', tag: 'table', children: [{ tag: 'caption', html: 'ExtJs Template Table'}], 185 style: 'width:200px; border: 1px solid blue;' 186 }; 187 var tab = Ext.DomHelper.append(divContent, tabTag); 188 189 //创建模版 190 var tpl = Ext.DomHelper.createTemplate({ tag: 'tr', children: [ 191 { tag: 'td', html: "{0}", style: "border: 1px solid blue;" }, 192 { tag: 'td', html: "{1}", style: "border: 1px solid blue;" } 193 ] 194 }); 195 Ext.each(data, function (item) { 196 tpl.append(tab, [item.Name, item.Html]); //筛入数据 197 }); 198 } 199 200 //使用ExtJs的XTemplate创建Table 201 function createExtJsXTemplate() { 202 var data = { Messages: [{ Name: "百度", Html: "<a href='#'>百度简介</a>" }, 203 { Name: "新浪", Html: "<a href='#'>新浪简介</a>" }, 204 { Name: "搜狐", Html: "<a href='#'>搜狐简介</a>"}] 205 }; 206 207 var divContent = Ext.get("divContent"); 208 var tpl = new Ext.XTemplate(//创建模版 209 '<table width="200px" cellspacing="1" cellpadding="1" border="1">', 210 '<caption>ExtJs XTemplate Table</caption>', 211 '<tpl for="Messages">', 212 '<tr><td>{Name}</td><td>{Html}</td></tr>', 213 '</tpl>', 214 '</table>' 215 ); 216 tpl.compile(); //模版编译一下 217 tpl.overwrite(divContent, data); //模版重写 218 } 219 </script> 220 </head> 221 <body> 222 <div id="divContainer" style="width: 500px; background-color: Teal; padding: 5px 10px 20px 5px"> 223 <div id="divTools"> 224 <input type="button" id="btnAjaxTable" class="buttonCSS" value="添加Ajax表格" onclick="ajaxData()" /> 225 <input type="button" id="btnSelAll" class="buttonCSS" value="添加全选表格" onclick="JQueryAjax();ExtJsAjax()" /> 226 <input type="button" id="btnCreateObjs" class="buttonCSS" value="创建其他对象" onclick="createJQueryObjs();createExtJsObjs()" /> 227 </div> 228 <div id="divContent" style="width: 100%; background-color: Yellow; padding-top: 3px; 229 padding-left: 5px; padding-bottom: 10px; text-align: center"> 230 </div> 231 </div> 232 </body> 233 </html>
服务端代码:
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Runtime.Serialization.Json; 6 using System.Text; 7 using System.Web; 8 using System.Web.Script.Serialization; 9 10 namespace JsJQueryExtJsReview.JQueryReview.Ajaxs 11 { 12 /// <summary> 13 /// AjaxHandler 的摘要说明 14 /// </summary> 15 public class AjaxHandler : IHttpHandler 16 { 17 18 public void ProcessRequest(HttpContext context) 19 { 20 context.Response.ContentType = "text/plain";//application/json text/plain 21 string JsonData = string.Empty; 22 23 System.Threading.Thread.Sleep(2000);//延迟2000毫秒 24 25 List<Message> list = initMessages(); 26 27 JsonData = GetJavaScriptData(list);//JavaScript序列化操作 28 JsonData = GetDataContractData(list);//DataContract序列化操作 29 30 context.Response.Write(JsonData); 31 } 32 33 /// <summary> 34 /// DataContractJsonSerializer序列化数据 35 /// </summary> 36 /// <param name="messages">信息对象集合</param> 37 /// <returns>信息对象Json串</returns> 38 private string GetDataContractData(List<Message> messages) 39 { 40 string json = string.Empty; 41 DataContractJsonSerializer dataContract = new DataContractJsonSerializer(messages.GetType()); 42 MemoryStream ms = new MemoryStream(); 43 dataContract.WriteObject(ms, messages); 44 json = Encoding.UTF8.GetString(ms.ToArray()); 45 return json; 46 } 47 48 /// <summary> 49 /// JavaScriptSerializer序列化数据 50 /// </summary> 51 /// <param name="messages">信息对象集合</param> 52 /// <returns>信息对象Json串</returns> 53 private string GetJavaScriptData(List<Message> messages) 54 { 55 string json = string.Empty; 56 JavaScriptSerializer javaScript = new JavaScriptSerializer(); 57 json = javaScript.Serialize(messages); 58 return json; 59 } 60 61 /// <summary> 62 /// 初始化数据 63 /// </summary> 64 /// <returns></returns> 65 private List<Message> initMessages() 66 { 67 List<Message> list = new List<Message>() { 68 new Message(){ Name="百度",Html="<a href='#'>百度简介</a>"}, 69 new Message(){ Name="新浪",Html="<a href='#'>新浪简介</a>"}, 70 new Message(){ Name="搜狐",Html="<a href='#'>搜狐简介</a>"} 71 }; 72 73 return list; 74 } 75 76 public bool IsReusable 77 { 78 get 79 { 80 return false; 81 } 82 } 83 } 84 85 public class Message 86 { 87 public string Name { get; set; } 88 public string Html { get; set; } 89 } 90 }
5.使用JQuery和ExtJs进行Ajax调用动态创建Table
主要是对JQuery、ExtJs的Ajax使用以及如何使用JQuery、ExtJs动态创建Table对象填充数据,简单实现CheckBox的全选操作。服务端的代码是第4点的一般处理程序。效果图:
代码如下:
1 //JQuery的Ajax方式取得数据,添加全选按钮 2 function JQueryAjax() { 3 var message = "JQuery信息加载中......"; 4 var divMessage = "<div style='color:green;'>" + message + "</div>"; 5 $("#divContent").html(divMessage); 6 7 $.ajax({ 8 type: "POST", 9 url: "../Ajaxs/AjaxHandler.ashx", 10 async: true, //异步加载信息 11 dataType: "json", 12 success: function (data) { 13 var message = "JQuery信息加载成功!"; 14 var divMessage = "<div style='color:green;'>" + message + "</div>"; 15 $("#divContent").html(divMessage); 16 17 createJQueryTable(data); 18 JQueryCHKBoxTable(data); 19 }, 20 error: function () { alert("请求失败!"); } 21 }); 22 } 23 24 function JQueryCHKBoxTable(data) { 25 var tab = $("<table/>", { width: "300px", cellSpacing: "1", cellPadding: "1", border: "1" }); 26 $("<caption/>").text("JQuery CheckBox Table").appendTo(tab); 27 28 var ths = $("<tr/>").appendTo(tab); 29 var th0 = $("<th/>").appendTo(ths); 30 $("<input/>", { type: "checkbox", id: "chAll" }).appendTo(th0); 31 $("<th/>", { text: "名称" }).appendTo(ths); 32 $("<th/>", { text: "简介" }).appendTo(ths); 33 34 $(data).each(function (index, item) { 35 var tr = $("<tr/>").appendTo(tab); 36 var td0 = $("<td/>").appendTo(tr); 37 $("<input>", { type: "checkbox", name: "chSingle" }).appendTo(td0); 38 $("<td/>").html(item.Name).appendTo(tr); 39 $("<td/>").html(item.Html).appendTo(tr); 40 }); 41 42 tab.appendTo($("#divContent")); 43 44 $("#chAll").click(function (obj) { 45 var chSingles = $("input:[name='chSingle']"); 46 $(chSingles).each(function (index, item) { 47 item.checked = $("#chAll")[0].checked; //$("#chAll"),查询出来的是一个集合 48 }); 49 }); 50 51 // $("#chAll")[0].onclick = function () {//$("#chAll"),查询出来的是一个集合 52 // var chSingles = $("input:[name='chSingle']"); 53 // $(chSingles).each(function (index, item) { 54 // item.checked = $("#chAll")[0].checked; 55 // }); 56 // } 57 } 58 59 //ExtJs的Ajax方式取得数据,添加全选按钮 60 function ExtJsAjax() { 61 var message = "ExtJs信息加载中......"; 62 var divMessage = "<div id='divMessage' style='color:green;'>" + message + "</div>"; 63 var divContent = Ext.get("divContent"); 64 Ext.DomHelper.append(divContent, divMessage); 65 66 Ext.Ajax.request({ 67 method: "POST", 68 url: "../Ajaxs/AjaxHandler.ashx", 69 async: true, //异步加载信息 70 success: function (response, opts) { 71 message = "ExtJs信息加载成功!"; 72 var divMessage = "<div style='color:green;'>" + message + "</div>"; 73 //Ext.get("divMessage").dom.innerHTML = message; 74 Ext.DomHelper.append(divContent, divMessage); 75 76 var data = Ext.util.JSON.decode(response.responseText); 77 createExtJsTable(data); //ExtJs创建Table 78 ExtJsCHKBoxTable(data); //ExtJs创建CheckBox的Table 79 }, 80 failure: function (response, opts) { alert("请求失败!"); } 81 }); 82 } 83 84 //ExtJs的CheckBox Table 85 function ExtJsCHKBoxTable(data) { 86 var divContent = Ext.get("divContent"); 87 var tabTag = { tag: "table", style: "width:300px;border:1px solid blue", children: [{ tag: "caption", html: "ExtJs CheckBox Table"}] }; 88 var tab = Ext.DomHelper.append(divContent, tabTag); //将table追加到divContent 89 90 //创建列头 91 var ths = { tag: "tr", children: [ 92 { tag: "th", style: "border:1px solid blue", children: [ 93 { tag: "input", type: "checkbox", id: "chkAll" } 94 ] 95 }, 96 { tag: "th", style: "border:1px solid blue", html: "名称" }, 97 { tag: "th", style: "border:1px solid blue", html: "简介" } 98 ] 99 }; 100 Ext.DomHelper.append(tab, ths); //将tr追加到table 101 102 Ext.each(data, function (item) {//遍历数据 103 var trTag = { tag: "tr", children: [ 104 { tag: "td", style: "border:1px solid blue", children: [{ tag: "input", type: "checkbox", name: "chkSingle"}] }, 105 { tag: "td", style: "border:1px solid blue", html: item.Name }, 106 { tag: "td", style: "border:1px solid blue", html: item.Html } 107 ] 108 }; 109 Ext.DomHelper.append(tab, trTag); //将tr追加到table 110 }); 111 112 Ext.get("chkAll").on("change", function (obj) { 113 var chkSingles = Ext.query("input[name='chkSingle']"); //Dom集合 114 Ext.each(chkSingles, function (item) { 115 item.checked = Ext.get("chkAll").dom.checked; 116 }); 117 }); 118 119 // Ext.get("chkAll").addListener("click", function (obj) { 120 // var chkSingles = Ext.query("input[name='chkSingle']"); //Dom集合 121 // Ext.each(chkSingles, function (item) { 122 // item.checked = Ext.get("chkAll").dom.checked; 123 // }); 124 // }); 125 }
6.使用JQuery和ExtJs简单创建对象
其实前面复杂的操作处理了,这个就比较简单,简单创建几个input对象。依然是第4点的页面,再加上下面2个脚本函数,代码如下
1 //JQuery创建其他对象 2 function createJQueryObjs() { 3 var divContent = $("#divContent").css("text-align", "left").append("<div>JQuery创建其他对象</div>"); 4 5 $("<input/>", { type: "button", val: "创建按钮" }).appendTo(divContent); 6 $("<br/>").appendTo(divContent); 7 $("<input/>", { type: "button", val: "添加样式", class: "buttonCSS" }).appendTo(divContent); 8 $("<br/>").appendTo(divContent); 9 $("<input/>", { type: "button", val: "添加事件", click: function () { 10 alert($(this).val() + ",测试成功!"); 11 } 12 }).appendTo(divContent); 13 $("<br/>").appendTo(divContent); 14 $("<input/>", { type: "text", id: "txt", val: '创建文本', css: { "background-color": "red"} }).appendTo(divContent); 15 $("<br/>").appendTo(divContent); 16 $("<input/>", { type: "radio", name: "sex", val: "男" }).appendTo(divContent); 17 $("<label/>", { text: "男" }).appendTo(divContent); 18 $("<input/>", { type: "radio", name: "sex", val: "女", checked: "true" }).appendTo(divContent); 19 $("<label/>", { text: "女" }).appendTo(divContent); 20 $("<br/>").appendTo(divContent); 21 } 22 23 //ExtJs创建其他对象 24 function createExtJsObjs() { 25 var divContent = Ext.get("divContent"); 26 Ext.DomHelper.append(divContent, "<hr/>ExtJs创建其他对象<br/>"); 27 var buttonTag = { tag: "input", type: "button", value: "ExtJs按钮" }; 28 Ext.DomHelper.append(divContent, buttonTag); 29 Ext.DomHelper.append(divContent, "<br/>"); 30 var textTag = { tag: "input", type: "text", id: "testText", value: "ExtJs文本框" }; 31 Ext.DomHelper.append(divContent, textTag); 32 }
使用原生JavaScript动态创建Table有些生硬,不太灵活;使用JQuery和ExtJs是各个API方法的调用,相对灵活些,代码也相对减小一些。
ExtJs一般不用Table来显示列表数据,一般直接用GridPanel直接绑定数据,显示数据,再加上CheckBox的多选功能。
先记下来吧,等有空了,把它整理一下。