為什么我的“刪除和添加”部分運(yùn)行良好,卻改不了背景顏色?window.onload=function()這部分代碼有問(wèn)題嗎?
<!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()?????? ?
????? {
??????? for(var i=0;i<tr.length;i++)
??????? {
??????????? tr[i].onmouseover=function()
??????????? {
???????????????? tr[i].style.backgroundColor="#f22";
??????????? }
????????? ?
?????????? tr[i].onmouseout= function()
?????????? {
?????????????? tr[i].style.backgroundColor="#ddd";
?????????? }
??????? }
????? }
??? function add()
???? {
???????? var tabl=document.getElementById("table");
???????? var btn=document.createElement("tr");
???????? var btn1=document.createElement("th");
???????? var btn2=document.createElement("th");
???????? var btn3=document.createElement("th");
????????? btn1.innerHTML="xh003";
????????? btn2.innerHTML="張小節(jié)";
????????? tabl.appendChild(btn);
????????? btn.appendChild(btn1);
????????? btn.appendChild(btn2);
????????? btn.appendChild(btn3);
???? }
?? ??? ??? ?
???? // 創(chuàng)建刪除函數(shù)
???? function cancel()
???? {
??????? var otest=document.getElementById("id1");
??????? var len=otest.childNodes.length;
??????? for(var i=0;i<len;i++)
??????? otest.removeChild(otest.childNodes[0]);
???? }
??? ?
???? function canc()
???? {
??????? var test=document.getElementById("id2");
??????? var leng=test.childNodes.length;
??????? for(var i=0;i<leng;i++)
??????? test.removeChild(test.childNodes[0]);
???? }
??? ?
? </script>
?</head>
?<body>
?? ??? <table border="1" width="50%" id="table">
?? ??? <tr>
?? ??? ?<th>學(xué)號(hào)</th>
?? ??? ?<th>姓名</th>
?? ??? ?<th>操作</th>
?? ??? </tr> ?
?? ??? <tr id="id1">
?? ??? ?<td>xh001</td>
?? ??? ?<td>王小明</td>
?? ??? ?<td><a href="javascript:;" onclick="cancel()">刪除</a></td> ?
?? ??? ?<!--在刪除按鈕上添加點(diǎn)擊事件? -->
?? ??? </tr>
?? ??? <tr id="id2">
?? ??? ?<td>xh002</td>
?? ??? ?<td>劉小芳</td>
?? ??? ?<td><a href="javascript:;" onclick="canc()" >刪除</a></td>? ?
?? ??? ?<!--在刪除按鈕上添加點(diǎn)擊事件? -->
?? ??? </tr> ?
?? ??? </table>
?? ??? <input type="button" value="添加一行" onclick="add()"? />?? <!--在添加按鈕上添加點(diǎn)擊事件? -->
?</body>
</html>
2019-11-07
你這代碼有兩個(gè)問(wèn)題,我截圖了
然后你檢查一下,你還少了一行代碼..? 你覺(jué)得你這個(gè)tr取到了嗎?? 你這tr哪里來(lái)的?
你要寫(xiě)一個(gè)var tr = document.getElementsByTagName('tr')