2017-01-17 82 views
0

我製作了一個腳本來使用頁面之間的淡入淡出過渡。它將頁面加載到div中,在舊的頁面中淡入淡出。使用jQuery刪除動態創建的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/

回答

1

假設你隨時刪除最近的一次,因爲對象不能直接指向它被刪除,您需要通過其父引用它。所以,如果您可以更新自己的HTML中至少有一個父DIV:

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

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

問候

+0

謝謝大衛。是的,我刪除了最近的一個。我從來沒有想過要把第一個孩子搬走。我刪除了lastDivId全局,現在它工作的很好。 –

0

我的答案基於@大衛·埃斯皮諾的帖子

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(); 
 
     } 
 
    }); 
 
    }); 
 
}
body, 
 
html { 
 
    height: 100%; 
 
    width: 100%; 
 
    padding: 0; 
 
    margin: 0; 
 
} 
 
.divContainer { 
 
    overflow: hidden; 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
    ; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

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