【问题标题】:How to remove div elements from the DOM tree one by one?如何从 DOM 树中一一删除 div 元素?
【发布时间】:2017-04-22 12:14:47
【问题描述】:

这里是my example

通过单击添加按钮,我添加了一张用户卡。 “清除按钮”删除所有卡片。如何通过点击每张卡片中的“关闭”图标一一移除卡片?

HTML 文件

<div class="header">
  <button id="clear" class="button clear">Clear</button>
  <button id="button" class="button add">Add user</button>
</div>
<div id="content">
</div>

JS 文件

var root = 'https://jsonplaceholder.typicode.com';
var index = 0;
$.ajax({
  url: root + '/posts/1/comments',
  method: 'GET'
}).then(function(data) {
  $("#button").click(function() {
  var notificationMessage = "Oops, there are no more user cards to display";
  if (index >= data.length ) {
    return alert(notificationMessage);
  }
  $("#content").append('<div id="card"><div class="title"><div class="image"></div><div id="name">'
    + data[index].name + '</div><span id="close"></span></div><div id="description">'
    + data[index].body + '<a href="mailto:" id="email">'
    + data[index].email + '</a></div></div>'
  );
  index++;
  // remove all cards from a list and return index equally [0], to be able add user card again.
  $("#clear").click(function() {
    $("#card").remove();
    index = 0;
  });
});
});

//How to remove card by clicking on the close button?

【问题讨论】:

  • 不要重复使用id。尝试使用类
  • 非常感谢大家!我是 jquery 的初学者。一个月前才开始玩。

标签: javascript jquery ajax


【解决方案1】:

您是否尝试过在card 元素中使用类? 因为id选择器只能获取第一个匹配元素

$.ajax({
    url: root + '/posts/1/comments',
    method: 'GET'
  }).then(function(data) {        
    $("#button").click(
      function() {
        var notificationMassage = "Oops, there are no more user cards to display";

        if (index >= data.length ) {
          return alert(notificationMassage);
        }

        $("#content").append('<div class="card"><div class="title"><div class="image"></div><div class="name">'
              + data[index].name + '</div><span class="close"></span></div><div class="description">' 
              + data[index].body + '<a href="mailto:" id="email">'
              + data[index].email + '</a></div></div>'
         );
        index++;

        // remove all cards from a list and return index equally [0], to be able add user card again.
        $("#clear").click(function() {
          $("#content").html('');
          index = 0;
        }); 
    });

要一一删除添加此代码

        // remove one cards from a list.
        $("#content").on("click", ".close", function() {
          $(this).closest('div.card').remove();
        });

【讨论】:

  • 关闭处理程序需要委托,否则将无法处理新添加的项目
【解决方案2】:

首先你需要把 id 改成 class。

这是解决方案:

codepen.io/ivanchuda/pen/xRjyJp

【讨论】:

    【解决方案3】:

    首先,id 应该是唯一的。我建议把你的改成类。

    $("#content").append('<div class="card"><div class="title"><div class="image"></div><div class="name">'
              + data[index].name + '</div><span class="close"></span></div><div id="description">' 
              + data[index].body + '<a href="mailto:" id="email">'
              + data[index].email + '</a></div></div>'
         );
    

    现在我们已经有了 close 类的所有关闭图标,我们可以为所有 .close 按钮添加以下侦听器,以仅删除包含它们的卡片。

    $(document).on('click', '.close', function(){
        $(this).closest('.card').remove(); // remove only closest '.card'
    });
    

    【讨论】:

    • $('.close').on('click', func() {}); 将无法工作,因为项目是动态添加的!
    • 不,Saumya Rastogi 是正确的。您仅将单个处理程序附加到所有匹配的现有项目。您需要将其设为on 的委托版本
    • 你们说得对,我一时糊涂了。更新了我的答案。
    【解决方案4】:

    首先,我会将 div 上的 ID 更改为 class,因为您要生成多张卡片。 ID 应该是唯一的。然后我会更改代码以在您的 close-span 中再添加一行:

    <span class="close" onclick="$(this).parent().parent().remove()"></span>
    

    【讨论】:

    • 我强烈建议不要将内联处理程序与 jQuery 结合使用。它使 HTML 膨胀并失去了 jQuery 事件添加的许多功能。改为使用 jQuery 委托事件处理程序。
    【解决方案5】:

    这样试试

    See the updated codeopen

    id 更改为 class 并匹配 parent() of parent() on()更重要

    $(document).on("click",".close",function() {
            $(this).parent().parent().remove()
    
            }); 
    

    【讨论】:

    • 使用 closest() 通常比 .parent().parent() 等更短,并且对 DOM 更改更健壮。
    【解决方案6】:

    您可以使用此代码来实现您想要的:

    $("body").on("click", ".close", function(e) {
      $(this).closest('.card').remove();
    });
    

    注意:请记住,在单个页面上仅使用单个 ID,而不是使用类来使其工作

    看到这个CodePen

    // jQuery on() method description
    .on( events [, selector ] [, data ], handler )
    

    详细了解 jQuery 的 on() 方法。

    希望这会有所帮助!

    【讨论】:

    • 这永远不会起作用,因为您有一个用于关闭的 ID 选择器。
    【解决方案7】:

    简短而不优雅的答案是:

    $("#content").on("click", "span[id=close]", function() {
        $(this).closest("div[id=card]").remove();
    });
    

    这应该可行,但您需要做得比这更好。您的 HTML 无效,因为 id 应该是唯一的,并且您对不同的项目使用相同的 id。您可以改用classes,或者确保标识符是唯一的。请注意,如果您使 HTML 有效,您的 SEO 将立即得到改善。如果你使用classes 而不是非唯一的ids,那么上面的脚本会变成这个:

    //content is unique, therefore it can remain an id
    $("#content").on("click", "span.close", function() {
        $(this).closest("div.card").remove();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-28
      • 2021-12-05
      • 2012-06-19
      • 2015-01-29
      • 2012-09-29
      • 1970-01-01
      • 2011-03-15
      • 2014-09-01
      相关资源
      最近更新 更多