為什么這個代碼只應(yīng)用到了row[2]?
? ? ? ? function on(tr1){
? ? ? ? ? ? tr1.onmouseover=function(){
? ? ? ? ? ? ? ? tr1.style.backgroundColor="#f2f2f2";
? ? ? ? ? ? }
? ? ? ? ? ? tr1.onmouseout=function(){
? ? ? ? ? ? ? ? tr1.style.backgroundColor="#fff";
? ? ? ? ? ? }
? ? ? ? } ? ??
? ? ? ? for(var i=0;i<rows.length;i++){
? ? ? ? ? ? on(rows[i]);
? ? ? ? ? ? ?}
?把上述代碼改寫成圖片中的代碼就只能應(yīng)用到第三行,chrome中檢查無語法錯誤;如果把變量tr1全部改成rows[i]則失效。chrome中檢查出row[i]是undefined
2016-04-29
<!DOCTYPE html>
<html>
<head>
? ?<title> new document </title>
? ?<meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
? ?<script type="text/javascript">
? ? ? ?window.onload = function(){
? ? ? ? ? ?var rows=document.getElementsByTagName("tr");
? ? ? ? ? ?for(var i=0;i<rows.length;i++){
? ? ? ? ? ? ? ?on(rows[i]);
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?
? ? ? ?function on(tr1)//把這個函數(shù)從 window.onload里拿出來,讓下面添加行的函數(shù)也能用
? ? ? ? ? ?tr1.onmouseover=function(){
? ? ? ? ? ? ? ?tr1.style.backgroundColor="#f2f2f2";
? ? ? ? ? ?}
? ? ? ? ? ?tr1.onmouseout=function(){
? ? ? ? ? ? ? ?tr1.style.backgroundColor="#fff";
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?
? ? ? ?function addRow(){
? ? ? ? ? ?var xh=prompt("請輸入學(xué)號:","xh0");
? ? ? ? ? ?var xm=prompt("請輸入姓名");
? ? ? ? ? ?var tr=document.createElement("tr");
? ? ? ? ? ?var td0=document.createElement("td");
? ? ? ? ? ?var td1=document.createElement("td");
? ? ? ? ? ?var td2=document.createElement("td");
? ? ? ? ? ?td0.innerHTML=xh;
? ? ? ? ? ?td1.innerHTML=xm;
? ? ? ? ? ?td2.innerHTML="<a href='javascript:;' onclick='deleteRow(this)'>刪除</a>";
? ? ? ? ? ?var tbody=document.getElementById("table").lastChild;
? ? ? ? ? ?while(tbody.nodeType!=1){
? ? ? ? ? ? ? ?var i=1;
? ? ? ? ? ? ? ?tbody=document.getElementById("table").childNodes[(document.getElementById("table").childNodes.length-1-i)];
? ? ? ? ? ? ? ?i++;
? ? ? ? ? ?}
? ? ? ? ? ?tbody.appendChild(tr);
? ? ? ? ? ?tr.appendChild(td0);
? ? ? ? ? ?tr.appendChild(td1);
? ? ? ? ? ?tr.appendChild(td2);
? ? ? ? ? ?on(tr);//動態(tài)添加的tr也要給綁上2個鼠標(biāo)事件
? ? ? ?}
? ? ? ?function deleteRow(obj){
? ? ? ? ? ?var tb=obj.parentNode.parentNode.parentNode;
? ? ? ? ? ?var tr=obj.parentNode.parentNode;
? ? ? ? ? ?tb.removeChild(tr);
? ? ? ?}
? ?</script>
</head>
<body>
<table border="1" width="50%" id="table">
? ?<thead><tr>
? ? ? ?<th>學(xué)號</th>
? ? ? ?<th>姓名</th>
? ? ? ?<th>操作</th>
? ?</tr></thead>
? ?<tbody>
? ?<tr>
? ? ? ?<td>xh001</td>
? ? ? ?<td>王小明</td>
? ? ? ?<td><a href="javascript:; " onclick="deleteRow(this)" >刪除</a></td> <!--在刪除按鈕上添加點擊事件 ?-->
? ?</tr>
? ?<tr>
? ? ? ?<td>xh002</td>
? ? ? ?<td>劉小芳</td>
? ? ? ?<td><a href="javascript:;" onclick="deleteRow(this)">刪除</a></td> ? <!--在刪除按鈕上添加點擊事件 ?-->
? ?</tr>
? ?</tbody>
</table>
<input type="button" value="添加一行" onclick="addRow()" /> ? <!--在添加按鈕上添加點擊事件 ?-->
</body>
</html>
2016-04-26
定義rows了嗎?
2016-04-25