项目中需要在js里拼接一个table,部分代码如下:
var result = " <table style='background-color:#def2f9;' cellspacing='1'>" + " <tr> " + "<td>" + "<table id='table_result'>"; result += "<tr>" + "<th class='td' >员工号</th>" + "<th class='td'>姓名</th>" + "<th class='td'>部门</th>" + "<th class='td'>职位</th>" + "<th class='td'>技能等级</th>" + "<th class='td'>联系电话</th>" + "<th class='td'>籍贯</th>" + "<th class='td'>现住址</th>" + "<th class='td'>在职状态</th>" + "<th class='td'>入职时间</th>" + "<th class='td'>离职时间</th>" + "<th class='td'>身份证号</th>" + "</tr>"; for(var i=0;i<staffViewList.length;i++) { result += "<tr id="+staffViewList[i].staff.staff_id+" onclick='onClickShowDetail(this.id)'"+" onmouseover='changeColor(this);' >"; result += "<td class='td'>"+staffViewList[i].staff.staff_number+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_name+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].dept.dept_name+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].job.job_name+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].level.level_name+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_phone+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_nativeplace+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_address+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_state+" "+"</td>"; result += "<td class='td'>"+timeStamp2String(staffViewList[i].staff.staff_startdate.time)+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_enddate+" "+"</td>"; result += "<td class='td'>"+staffViewList[i].staff.staff_idcard+" "+"</td>"; result += "</tr>"; } result += "</table></td> </tr></table>"; $("div_select_result").innerHTML = result;
先看下面两句代码有什么不一样的地方
第一种:
result += "<tr id="+staffViewList[i].staff.staff_id+" onclick='onClickShowDetail(this.id)'"+" onmouseover='changeColor(this);' >";
第二种:
result += "<tr id="+staffViewList[i].staff.staff_id+"onclick='onClickShowDetail(this.id)'"+"onmouseover='changeColor(this);' >";
其中,第二种写法中的onclick和onmouseover事件是执行不出来的,原因在于方法名前少加了一个空格,这样拼接出来的html文档中方法名和前面的属性混在一起,浏览器就无法区分开来,所以当我们在拼接html时一定要想象着它们拼接出来的样子,哪怕多加一个空格 也不要少了一个空格。
最后,空格留在哪儿可以根据自己的习惯,放在某一属性前、后或者单独写成+“ ”+也可以。