简体   繁体   中英

Clean the CSS that was added while loading Ajax content

I am appending an HTML document into my current page using Ajax, and removing those added divs when the close button is pressed. The problem is that when I close, the divs are removed from the document but the CSS <link rel="stylesheet" href="style.css"> are not removed, and the number keep increasing as I load and unload Ajax content. How to completely remove the loaded document with the header content (css, js) of that page?

edit: i dont know why people dont want to answer but they just come to negative voting. this is the code that i have used to add(append the html document)

$(function(){
              $("a[rel='tab']").click(function(e){
                pageurl = $(this).attr('href');
                $.get(pageurl, function(html) {
                          $(html).hide().appendTo('body').fadeIn(500);
                      }, 'html');

                //to change the browser URL to the given link location
                if(pageurl!=window.location){
                  window.history.pushState({path:pageurl},'',pageurl);
                }
                //stop refreshing to the page given in
                return false;
              });
            });

and this code to remove the divs

function close(){

        $("#mainContent").fadeOut(500, function() { $(this).remove(); });
        window.history.back();
} ;

I can't see the document that you are attempting to add/remove, but I'm guessing it looks something like this:

<link rel="stylesheet" href="style.css">
<div id="main-content">
  <p>Blah blah blah</p>
</div>

So when you add that content, the whole thing is inserted. When you remove it, you are only removing the div#main-content . To remove everything, two ideas come to mind:

  • Preferably, wrap the document in another <div> and remove that instead
  • Alternatively, you could select <link> elements that are siblings of the 'div#main-content`, but that has the potential to be more unpredictable.

If the document you are adding doesn't look like that, then please explain in the OP what it does look like and where the <link> elements are coming from.

If you are doing something like a HTML preview in another page, look into creating an iframe instead. Use AJAX to create a temporary URL as the source. The advantage is that you avoid conflicts that occur when you effectively merge two DOMs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM