开发者

clear DOM jquery

I have an interface where I can switch between tabs, and everytime I do that, load() function is called and loads some html to a div.

The thing is, even when I switch to another tab, the previous tab content stays in the DOM, and I don't want that, because I need to have duplicate id's and it's not very a optimal memory usage.

So basically, the question is, how do I clean the DOM from what was loaded before into that div, when I switch to another tab?

It would be even 开发者_运维技巧better, if I could name the loaded contents or something and then delete from the DOM, because I can't always know where the contents have been loaded.


Use the .empty() method on the div-element that contains the html you want to remove.

If you don't know which element that is, you have to bind the select event (if you use jQuery UI Tabs) for the tabs so you can store which tab is currently selected and also to know which one was previously selected.

Example:

var selectedTab;
$("#tabs").bind("tabsselect", function(event, ui) {
    if (selectedTab) {
        selectedTab.find("div").empty();
    }
    selectedTab = ui.panel;
});

You can also bind the above at creation-time of the tabs widget by passing the anonymous function as an option:

select: function(event, ui) { ... }


@Markus Ekwall: You need to surround selectedTab.find[...] with jQuery or else you'll get "selectedTab is not a function".

$(selectedTab).find("div").empty(); // or jQuery(selectedTab).find("div").empty();


In the select selector, empty out the previously selected tab. This works.

$( "#tabs" ).tabs( { select: function(event, ui) {

    var selectedPanel = $("#tabs div.ui-tabs-panel:not(.ui-tabs-hide)");
    $(selectedPanel).empty();


assuming the div container has id just use remove, like:

$("#id").remove();

in case you are using plain JavaScript:

var tab = document.getElementById("id");

if (tab.hasChildNodes())
{
    while (tab.childNodes.length >= 1)
    {
        tab.removeChild(tab.firstChild);
    } 
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜