【问题标题】:Removed DOM element still appears on the page [duplicate]移除的 DOM 元素仍然出现在页面上[重复]
【发布时间】:2023-03-13 08:22:01
【问题描述】:

我正在尝试动态添加/删除 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>

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:

    您的 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

    我在这里在#ex 元素上使用empty() 来保存选择器,它与remove() 具有相同的行为,除了在元素的子元素上执行,而不是在元素本身上执行。

    【讨论】:

      猜你喜欢
      • 2018-08-07
      • 2012-07-27
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 2012-10-22
      • 2013-05-19
      相关资源
      最近更新 更多