删除的DOM元素仍然出现在页面上

时间:2014-07-21 17:01:02

标签: javascript jquery html dom

我试图动态添加/删除DOM元素(id =" result")。添加似乎工作正常,但删除后元素仍然出现在页面上。

这里发生了什么?我做错了什么?

这是我的代码:

<!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>

1 个答案:

答案 0 :(得分: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()具有相同的行为,除了对元素的子元素执行,而不是元素本身

相关问题