2015-02-10 180 views
0

我试图删除所有行后删除表,但不知何故,我不能检查表是否删除所有行后有子级。
我不明白为什么寻找子元素长度不工作在这里?有什么建议么 ?行删除后删除表

<!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(); 
} 
+0

注意,表由THEAD和TBODY标签的 – 2015-02-10 16:48:19

+0

我们能看出你的JavaScript,请。 - 对不起,我现在看到它 – 2015-02-10 16:49:04

回答

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

这将帮助你

0

可以代替试试这个:

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

浏览器通常会增加<tbody><thead>标签进入,即使他们不是在你的HTML表格,这样行并不是唯一的孩子。上面的代码只是查找行。

+0

你应该能够检查'length'是否是falsy('if(!$(sel).length)'),而不是确保它小于1。 – ssube 2015-02-10 16:51:18