2014-07-21 52 views
1

我試圖動態地添加/刪除DOM元素(id =「result」)。添加似乎工作正常,但刪除後,該元素仍然出現在頁面上。刪除的DOM元素仍然出現在頁面上

這裏發生了什麼?我究竟做錯了什麼?

這裏是我的代碼:

<!DOCTYPE html> 
<html> 
    <body> 
    <script> 
     function clearResult() { 
     if (document.getElementById("result") != null){ 
      alert("remove #result"); 
      $("#result").remove(); 
      if (document.getElementById("result") != null) { 
       alert("#result still exists"); 
      } 
     } 
     alert("Exiting clearResult"); 
     } 

     function search() { 
     clearResult(); 
     if (document.getElementById("result") == null) { 
      alert("add #result"); 
      $('<table id="result"><tr>I am a table</tr></table>').appendTo('#ex'); 
     }     
     }  
    </script> 

    <div> 
     <button id="search" onclick="search()" value="Send">Search</button> 
    </div>  
    <div id="ex"> 
     @*Add result table here dynamically*@ 
    </div> 

    </body> 
</html> 
+0

TD在哪裏? ? –

回答

5

你的HTML是無效的。表內的內容需要位於td標記中。如果沒有這些,你的代碼被呈現爲:

I am a table 
<table id="result"><tr></tr></table> 

你可以看到,然後去除#result元素顯得無能爲力,因爲文本不消失。如果你改變你的代碼,包括td元素,它工作正常:

$('<table id="result"><tr><td>I am a table</td></tr></table>').appendTo('#ex'); 

Example fiddle


請注意,您也可以大量簡化代碼。在使用jQuery刪除元素之前,您不需要檢查元素的存在。此外,您應該使用jQuerys事件處理程序,而不是過時的on屬性。試試這個:

<div> 
    <button id="search" value="Send">Search</button> 
</div> 
<div id="ex"></div> 
$('#search').click(function() { 
    $('#ex').empty().append('<table id="result"><tr><td>I am a table</td></tr></table>'); 
}); 

Updated fiddle

我用empty()這裏#ex元素保存一個選擇,它具有相同的行爲remove(),除了在元素的兒童進行的,不元素本身。

相關問題