删除行后删除表

时间:2015-02-10 16:45:25

标签: javascript jquery html5

我试图在删除所有行后删除表,但不知怎的,在删除所有行后我无法检查表是否有子项。
我不明白为什么寻找子元素长度在这里不起作用?有什么建议吗?

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>table manipulation </title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="stylesheet.css" />
        <script src="..//jquery-2.1.3.min.js"></script>
        <script src="table.js" type="text/javascript"></script>
    </head>
    <body>
        <table id = "table1">
  <tr id = "1">
    <td id = "information1"> i m the first row !</td>
    <td><button id = "button1" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td> 
  </tr>
  <tr id = "2">
   <td id = "information2"> i m the second row !</td>
    <td><button id = "button2" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td> 
  </tr>
   <tr id = "3">
   <td id = "information3" > i m the third row !</td>
    <td><button id = "button3" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td> 
  <tr id = "4">
   <td id = "information4" > i m the fourth row !</td>
    <td><button id = "button4" class = "buttonclass" onClick="reply_click(this.id)"> destroy ! </button></td> 
  </tr> 
       </table>
        <div id = "newtable"> </div>
    </body>
</html>


var id ; 
var table = $('<table></table>').addClass('foo');

function destroy(){
    var theParent = document.querySelector("#table1");
   var parent = $("#" + id).parent();
  $("#" + id).fadeOut( "slow", function() {
      $(parent).closest('tr').remove();
      alert(theParent.innerHTML);

  });


    var row = $('<tr</tr>').addClass('bar').text(parent.siblings().html());
    table.append(row);
   $("#newtable").append(table);
  parent.siblings().remove();



theParent.addEventListener("click", doSomething, false);


}
function doSomething(e) {

  if($("#table1").children().length < 1 ){
     theParent.remove();
  }


}

function reply_click(clicked_id)
{
    id = clicked_id;
    destroy();
}

2 个答案:

答案 0 :(得分:1)

function doSomething(e) {
  if($("#table1 tr").length <= 1 ){
     theParent.remove();
  }
}

这会对你有所帮助

答案 1 :(得分:0)

你可以试试这个:

if($("#table1").find('tr').length < 1 ){
   theParent.remove();
}

浏览器通常会将<tbody><thead>标记添加到表中,即使它们不在您的HTML中,因此行不是唯一的子项。上面的代码只是查找行。