Show()方法从dom中删除HTML元素,而不是显示它

show() method removes the html element from dom instead of displaying it

本文关键字:元素 显示 HTML 删除 方法 dom Show      更新时间:2023-09-26

我有这个代码,

<?php for($i = 1; $i <= 5; $i++) { ?>
  <div class="file-add-row" style="display:none;">Some content</div>
<?php } ?>
<div id="add-file-plus">Add File</div>

, JS为

$('#add-file-plus').live('click', function () {
  if($('div.file-add-row:visible').length == 0) {
    $('div.file-add-row:hidden:first').show();
  } else {
    $('.file-add-row:hidden:first').removeAttr("style").insertAfter($('.file-add-row:visible:last'));           
    }
});

现在,我的问题是,当我第一次点击添加按钮,第一个"文件添加行"div显示。但是当我第二次点击添加按钮时,页面上什么也没有发生。相反,它只是从dom中完全删除那个div。

我只是一个jquery的初学者,所以可能有一些东西我忽略了。有人知道是怎么回事吗?

当你这样做的时候:

$('.file-add-row:visible:last')

:

$('.file-add-row:hidden:first').removeAttr("style")

它们都指向同一个对象。如果你试图在自己之后插入一个对象,它最终会从DOM中移除自己。

将JS更改为:

$('#add-file-plus').live('click', function () {
  if($('div.file-add-row:visible').length == 0) {
    $('div.file-add-row:hidden:first').show();
  } else {
    var last_visible = $('.file-add-row:visible:last')
    $('.file-add-row:hidden:first').removeAttr("style").insertAfter(last_visible);       
  }
});

演示(点击"添加文件"):https://jsfiddle.net/woxd2jbf/1/

这是一个没有jQuery的版本,只是简单的JavaScript,它将与div一起工作,就像它与按钮,ul和li一样。详细信息在源代码中进行了注释。

关键方法
  • 版本()
  • 列表末尾()

恰好

片段

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <!--This <li> is a template to clone-->
  <li class="row" style='display:none'>Some content</li>
  <!--This is the empty list to be populated with clones-->
  <ul id='list'>
  </ul>
  <!--This button will have an eventListener 
that will execute a function when it is clicked-->
  <button id="add">Add File</button>
  <script>
    /* Reference each element involved in process */
     // The button
    var add = document.getElementById('add');
     // The list
    var list = document.getElementById('list');
     // The first li
    var row = document.querySelector('.row:first-of-type');
    /* 
      1. Button will listen for a `click`
      2. Create a clone of the first li
      3. Add clone as the last child of list
      4. Set clone's display property to block 
      so it's visible
    */
    add.addEventListener('click', function(e) {
      var clone = row.cloneNode(true);
      list.appendChild(clone);
      clone.style.display = 'block';
    }, false);
  </script>
</body>
</html>

(.file-add-row:隐藏:首先)美元.removeAttr("风格").insertAfter($('。file-add- row:visible:last'));,由于这一行发生了问题。因为它首先删除了使其可见的style属性,所以$('。file-add- row:visible:last')返回自身。像下面这样重构以存储可见代码的引用:

$(function () {
    $('#add-file-plus').live('click', function () {
        if ($('div.file-add-row:visible').length == 0) {
            $('div.file-add-row:hidden:first').show();
        } else {
            var $el = $('.file-add-row:visible:last');
            $('.file-add-row:hidden:first').removeAttr("style").insertAfter($el);
        }
    });
})