版本 V3
实现基准:自定义表头内容,根据表头,拼装table和tr、td等内容。
如图所示:这些就是表头,在模板里面可能不同比赛,不同描述,这个由编辑定义。
代码如何实现呢?
基本上都是拼装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+='<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"};