版本 V3
實作基準:自定義表頭内容,根據表頭,拼裝table和tr、td等内容。
如圖所示:這些就是表頭,在模闆裡面可能不同比賽,不同描述,這個由編輯定義。
<a href="http://jooben.blog.51cto.com/attachment/201005/19/253727_1274230768JxjZ.png"></a>
代碼如何實作呢?
基本上都是拼裝html,剛剛利用了一次json對象,這次再來:
注釋掉所有包含球員球隊資料的table内容<!---->
定義如下資料:
var th_names_json = {"選手":"name","第一節":"section_1","第二節":"section_2","第三節":"section_3","第四節":"section_4","加時1":"overtime_1","加時2":"overtime_2","總分":"totalScore"};
這裡就定義了這些内容:
<tr>
<th>選手</th>
<th>第一節</th>
<th>第二節</th>
<th>第三節</th>
<th>第四節</th>
<th>加時1</th>
<th>加時2</th>
<th>總分</th>
</tr>
疊代th_names_json對象,即可實作,較完整代碼:
var listSize = 2;
function init(){
var table_basic_html = '<table ;100%" border="0" align="center" cellpadding="0" cellspacing="1" class="lTb05">';
var th_names_json = {"選手":"name","第一節":"section_1","第二節":"section_2","第三節":"section_3","第四節":"section_4","加時1":"overtime_1","加時2":"overtime_2","總分":"totalScore"}
var th_names_len = getJsonLength(th_names_json);
var item_i = 0;
for(var item in th_names_json){
if(item_i==0){
table_basic_html+="<tr>";
}
table_basic_html+="<th>"+item+"</th>";
if(item_i==th_names_len-1){
table_basic_html+="</tr>";
item_i++;
}
for(var i=0;i<listSize;i++){
id = i+1;
table_basic_html+='&lt;tr id="tr_'+id+'">';
var item_ini= 0;
for(var item in th_names_json){
if(item_ini==0){
table_basic_html+='<td class="tl" id="t_'+id+'_'+th_names_json[item]+'">立陶宛男子籃球'+id+'</td>';
}else{
table_basic_html+='<td><input id="t_'+id+'_'+th_names_json[item]+'" name="t_'+id+'_'+th_names_json[item]+'" type="text" class="mInput04" value="" size="8" /></td>';
}
if(item_ini==th_names_len-1){
table_basic_html+='</tr>';
}
item_ini++;
table_basic_html+="</table>";
alert(table_basic_html);
document.write(table_basic_html);
}
function getJsonLength(data){
var objarray = new Array(); // 用來存儲變量名稱的數組
for(var i in data){
objarray[objarray.length++] = i;
}
return objarray.length;
init();
再定義一個json對象: json =
{"t_1_name":"美國男子籃球隊",
"t_1_section_1":"100","t_1_section_2":"60","t_1_section_3":"30","t_1_section_4":"10","t_1_totalScore":"190","t_2_name":"立陶宛男子籃球隊","t_2_section_1":"10","t_2_section_2":"6","t_2_section_3":"3","t_2_section_4":"1","t_2_totalScore":"20"};
效果如圖:
<a href="http://jooben.blog.51cto.com/attachment/201005/19/253727_1274230769Pn8t.png"></a>
這個時候,table還沒有注入,“确定”之後:
<a href="http://jooben.blog.51cto.com/attachment/201005/19/253727_1274230770xHoc.png"></a>
ok,版本V3算是搞定,代碼還可以優化的!
本文轉自jooben 51CTO部落格,原文連結:http://blog.51cto.com/jooben/317692