How can I use jQuery.load to replace a div including the div

前端 未结 13 1557
半阙折子戏
半阙折子戏 2020-11-27 14:40

I have a div with the id of \"secondHeader\" and I want to replace that entire div with another div with the same id of \"secondHeader\" but instead of replacing it , it jus

相关标签:
13条回答
  • 2020-11-27 15:19

    Could you refine your selector in the load() method?

    For example,

    $("#secondHeader").load("/logged-in-content.html #secondHeader > *");
    

    This way, you're not grabbing the div itself, you're grabbing its contents.

    0 讨论(0)
  • 2020-11-27 15:19

    You want to wrap in div before inserting it.

    $.ajax({
        url: "/logged-in-content.html",
        success: function(response){
            var loadedheader = $("<div/>").append(
            response.replace(/<script(.|\s)*?\/script>/g, "")
            ).find('#secondHeader > *').html();
            $("#secondHeader").append(loadedheader);
        }
    });
    
    0 讨论(0)
  • 2020-11-27 15:21

    I think the best way is to use get instead of load. In your case you can do like this:

    $.get("/logged-in-content.html #secondHeader", function(data) {
         $("#secondHeader").replaceWith(data);
    });
    

    [Edit: removed a paren]

    Update: If /logged-in-content.html has more than just the code you need, you can wrap the returning data in another jQuery object and use .find() to extract the container. Try this:

    $("#secondHeader").replaceWith($(data).find("#secondHeader"));

    0 讨论(0)
  • 2020-11-27 15:21

    I had this issue as well, but I was able to use .load by restructuring the code like so: (jade)

    div#view
       div.content
          block content
    

    and the script like so...

    $("#view").load( $(this).attr("href") + " div.content" )
    

    so target the child instead of the same tag.

    0 讨论(0)
  • 2020-11-27 15:26

    Using $.get() worked for me but I had to extract the container from the response document first:

    $.get("/page.html", function (data) {
        var elem = $(data).find('#container');
        $("#puthere").replaceWith(elem);
    });
    
    0 讨论(0)
  • 2020-11-27 15:26

    I always have a jQuery function defined like this:

        jQuery.fn.loadOuter = function( url, callback )
        {
            var toLoad = $(this);
            $.get(url, function( data ) {
                toLoad.replaceWith( data );
                if (callback != null && callback != undefined)
                    callback();
            });
        }
    

    Then I can either say

    $(...).load(url)
    

    or

    $(...).loadOuter(url)
    

    The second one does what you want to do. I also have a function called loadInner which just calls load for what its worth.

    0 讨论(0)
提交回复
热议问题