2013-11-22 26 views
1

我創建了一個非常基本的表格和複選框佈局。我在表中有八個文本框和八行。我只是試圖在複選框檢查上添加行,並取消選中。node.removeChild(子)的怪異行爲

所以,我使用相同的兩個功能。

function show(input){ 
    var tbody = document.getElementById("tbody"); 
    if(document.contains(document.getElementById("tr"+input))) 
    { 
     hide('tr'+input); 
    } 
    if(!document.contains(document.getElementById("tr"+input))) 
    { 
     tbody.appendChild(getRow(input)); 
    } 
} 

function hide(input){ 
    if(document.contains(document.getElementById(input))) 
    { 
     var child = document.getElementById(input); 
     child.parentNode.removeChild(child); 
     child.parentNode.removeChild(child); 
    } 
} 

在隱藏功能,如果我只用一個removeChild之言,這是行不通的。在使用兩個時,在控制檯中報告錯誤,但它完美地工作。

如果有人知道原因,請告訴我,因爲在代碼中留下錯誤是不道德的。

編輯#1:JsFiddle

+2

你能否提供一個[小提琴](http://jsfiddle.net/)來演示這個問題? – robertklep

+0

你的代碼看起來不錯,但是幫助你沒有小提琴對任何人來說都是非常耗時的。 – Chandranshu

+0

嘿傢伙,請檢查jsFiddle鏈接加入 –

回答

2

你的問題是這樣的功能:

function show(input) { 
    var tbody = document.getElementById("tbody"); 
    if (document.contains(document.getElementById("tr" + input))) { 
     hide('tr' + input); 
    } 
    if (!document.contains(document.getElementById("tr" + input))) { 
     tbody.appendChild(getRow(input)); 
    } 
} 

首先,檢查節點存在,如果是這樣,隱藏它。接下來,你總是檢查節點是否是而不是存在,如果是的話,你添加它。當節點剛剛隱藏時,第二次檢查將是true(因爲您剛剛刪除了該節點),並且該節點再次被添加回來。

所以改寫爲這樣的:

function show(input) { 
    var tbody = document.getElementById("tbody"); 
    if (document.contains(document.getElementById("tr" + input))) { 
     hide('tr' + input); 
    } else if (!document.contains(document.getElementById("tr" + input))) { 
     tbody.appendChild(getRow(input)); 
    } 
} 

fiddle

+0

很好...明白我的錯 –

2

似乎有一個與元素的直接重繪的問題,這裏是爲我工作

var child = document.getElementById(input); 
setTimeout(function(){ 
     child.parentNode.deleteRow(child.rowIndex - 1);  
}, 1); 

而一個骯髒的方式在附加/刪除表格元素時使用特定於表格的方法是安全的。

+0

真棒..工作完美 –