使用jQuery删除动态创建的DIV

时间:2017-01-17 02:25:16

标签: jquery html5

我创建了一个脚本来使用页面之间的淡入淡出过渡。它将页面加载到div中,在旧的页面中逐渐淡入。

我试图在覆盖它之后删除一个div,使用jQuery完成淡入淡出。

当我调试代码时,div仍然出现在DOM中。

var lastDivId;

var firstURL = "https://jsfiddle.net/user/dashboard/";
var secondURL = "https://jsfiddle.net/user/dashboard/edit/";

$(document).ready(function() {
  setTimeout(function() {
    openPopup(firstURL, 1);
  }, 1); //load the start page
  setTimeout(function() {
    openPopup(secondURL, 2);
  }, 3000); //load another page 3 seconds later
});

function openPopup(url, divID) {
  divID = "i" + divID; // ID can't just be a number
  $(document.body).append('<div class="divContainer" id="' + divID + '"><object data="' + url + '" /></div>');
  $('#' + divID).ready(function() {
    $('#' + divID).css("display", "none"); //make it visible after it's ready. it must be visible for it to get ready.
    $('#' + divID).fadeIn(2000, function() {
      // FadeIn complete. now remove old layer
      $('#' + lastDivId).remove();
      lastDivId = divID;
    });
  });
}

这是小提琴:https://jsfiddle.net/Henry3000/amh4upb4/3/

2 个答案:

答案 0 :(得分:1)

假设您始终删除最新的对象,因为无法直接删除对象,您需要通过其父对象引用它。所以万一你可以更新你的html至少有一个父div:

<div id='divParent'></div>

https://jsfiddle.net/thyysbxr/1/

此致

答案 1 :(得分:0)

我的答案基于@David Espino的帖子

&#13;
&#13;
var firstURL = "http://stackoverflow.com/help/badges"; //shoud be same domain as script
var secondURL = "http://stackoverflow.com/questions/41688143/remove-dynamically-created-div-with-jquery/41688743#41688743"; //should be same domain as sript

$(document).ready(function() {
  openPopup(firstURL, 1); //load the start page
  setTimeout(function() {
    openPopup(secondURL, 2);
  }, 3000); //load another page 3 seconds later 
});

function openPopup(url, divID) {
  var globalParent = $('#divParent');
  divID = "i" + divID; // ID can't just be a number
  $(globalParent).append('<div class="divContainer" id="' + divID + '"><object data="' + url + '" /></div>');
  $('#' + divID).ready(function() {
    $('#' + divID).css("display", "none"); //make it visible after it's ready. it must be visible for it to get ready.
    $('#' + divID).fadeIn(2000, function() {
      // FadeIn complete. now remove old layer
      if (globalParent.children().length > 1) {
        // this is removing the previously one added
        $(globalParent.children()[0]).remove();
      }
    });
  });
}
&#13;
body,
html {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}
.divContainer {
  overflow: hidden;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  ;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='divParent'></div>
&#13;
&#13;
&#13;