为什么这样不能实现删除函数

来源:9-22 编程练习

jimuw

2016-07-08 15:36

<!DOCTYPE html>

<html>

 <head>

  <title> new document </title>  

  <meta http-equiv="Content-Type" content="text/html; charset=utf8"/>   

  <script type="text/javascript"> 

  

      window.onload = function(){

                  

     // 鼠标移动改变背景,可以通过给每行绑定鼠标移上事件和鼠标移除事件来改变所在行背景色。

         

     

 

}

     

      // 编写一个函数,供添加按钮调用,动态在表格的最后一行添加子节点;

     

   

     

     // 创建删除函数

     function clears(x){

      var clearTr=document.getElementsByTagName('tr')[x];

      clearTr.parentNode.removeChild[clearTr];

     }



  </script> 

 </head> 

 <body> 

  <table border="1" width="50%" id="table">

  <tr>

<th>学号</th>

<th>姓名</th>

<th>操作</th>

  </tr>  


  <tr>

<td>xh001</td>

<td>王小明</td>

<td><a href="javascript:;"onclick="clears('1')">删除</a></td>   <!--在删除按钮上添加点击事件  -->

  </tr>


  <tr>

<td>xh002</td>

<td>刘小芳</td>

<td><a href="javascript:;"onclick="clears('2')" >删除</a></td>   <!--在删除按钮上添加点击事件  -->

  </tr>  


  </table>

  <input type="button" value="添加一行"  />   <!--在添加按钮上添加点击事件  -->

 </body>

</html>


写回答 关注

4回答

  • shuaishuaiDA
    2016-07-08 16:48:22
    已采纳

    clearTr.parentNode.removeChild(clearTr);


    jimuw

    一楼我已经给出了答案,但还是要感谢

    2016-07-08 22:51:34

    共 1 条回复 >

  • 慕粉3591791
    2016-07-10 15:33:35

    你这个问题比较多啊。首先removeChild[clearTr]==》removeChild(clearTr),其次clearTr不一定是你要的那个clearTr,你要考虑到空格node,还有一个就是删除了之后对x的影响。

  • qq_V5_0
    2016-07-08 16:02:11

    //删除函数

    function clieaRow(obj){

        

        var table = document.getElementById("table").lastChild;

        //点击事件从a标签触发,那么从a出发找到当前要删除的tr

        var tr =obj.parentNode.parentNode;

        //删除节点

        table.removeChild(tr)

    }

  • jimuw
    2016-07-08 15:55:27

    clearTr.parentNode.removeChild[clearTr];

    应该改为

    clearTr.parentNode.removeChild(clearTr);

    用错括号了,我说呢。。

JavaScript进阶篇

本课程从如何插入JS代码开始,带您进入网页动态交互世界

467393 学习 · 21877 问题

查看课程

相似问题