我如何使用jQuery.load来替换包括div的div

时间:2022-11-25 14:50:26

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 just adds the loaded div inside the first one.

我有一个id为“secondHeader”的div,我想用另一个具有相同id“secondHeader”的div替换整个div,但不是替换它,而是将加载的div添加到第一个div中。

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

This is what happens...

这就是发生的事情......

<div id="secondHeader"><div id="secondHeader"></div></div>

What I want to happen is the secondHeader div from the ajax load to totally replace the secondHeader in the initial page.

我想要发生的是从ajax加载的secondHeader div到完全替换初始页面中的secondHeader。

I know it sounds dumb, but here's what I'm trying to accomplish...When a user is not logged in, they see a non-logged in header. I am using ajax to allow the person to log into the site and I want to replace the non-logged in header with the logged in one via ajax.

我知道这听起来很愚蠢,但这就是我想要完成的事情......当用户没有登录时,他们会看到未登录的标题。我正在使用ajax来允许此人登录该站点,我想通过ajax将已登录的标头替换为未登录的标头。

I have tried everything I know such as...

我已经尝试过我所知道的一切,比如......

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

...and using .remove() before hand...

...并在手前使用.remove()...

Any ideas?

有任何想法吗?

12 个解决方案

#1


41  

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

我认为最好的方法是使用get而不是load。在你的情况下你可以这样做:

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

[Edit: removed a paren]

[编辑:删除了一个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:

更新:如果/logged-in-content.html不仅仅包含您需要的代码,您可以将返回的数据包装在另一个jQuery对象中,并使用.find()来提取容器。尝试这个:

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

$( “#secondHeader”)replaceWith($(数据).find( “#secondHeader”));

#2


59  

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

你能在load()方法中改进你的选择器吗?

For example,

例如,

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

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

这样,你就不会抓住div本身,而是抓住它的内容。

#3


28  

Another way that worked best for me:

另一种最适合我的方式:

$('#div_to_replace').load('/ajax/loader', function() {
    $(this).children(':first').unwrap();
});

#4


8  

Final Answer:

最终答案:

$.fn.loadWith = function(u){var c=$(this);$.get(u,function(d){c.replaceWith(d);});};
$("#test").loadWith("somelink.html");

jQuery load adds the response INTO the element selected. jQuery's replaceWith REPLACES the selected element.

jQuery load将响应INTO添加到所选元素中。 jQuery的replaceWith替换所选元素。

<div id="curElement">start</div>

$("#curElement").load("somelink.html");
will result in:
<div id="curElement">What ever was in somelink.html</div>


$("#curElement").replaceWith("somelink.html");
will result in:
What ever was in somelink.html

I suggest adding a function to jQuery that does both:

我建议在jQuery中添加一个函数来执行这两个操作:

$.fn.loadWith = function(u){
    var c=$(this);
    $.get(u,function(d){
        c.replaceWith(d);
    });
};
$("#test").loadWith("somelink.html");

#5


3  

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

使用$ .get()为我工作,但我必须首先从响应文档中提取容器:

$.get("/page.html", function (data) {
    var elem = $(data).find('#container');
    $("#puthere").replaceWith(elem);
});

#6


2  

$.load isn't really the best choice here since that function's intended to just fill in the contents of a div, as you've seen. You can just use $.get instead and set the callback function to replace your original div, or change logged-in-content.html to exclude the div.

$ .load实际上并不是最好的选择,因为正如你所见,该函数只是用来填充div的内容。您只需使用$ .get并设置回调函数来替换原始div,或更改logged-in-content.html以排除div。

Also be aware that as a Javascript-based solution, if your users look at the source, they'll see that they can get access to logged-in-content.html by just typing it in their address bar if you're not securing it somehow else.

另请注意,作为基于Javascript的解决方案,如果您的用户查看源代码,他们会看到只要您不确保安全,只需在地址栏中键入内容即可访问logged-in-content.html不知何故。

#7


2  

I always have a jQuery function defined like this:

我总是有一个像这样定义的jQuery函数:

    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.

第二个做你想做的事。我还有一个名为loadInner的函数,它只调用load来实现它的价值。

#8


1  

var target = '#secondHeader';
var pathname = '/logged-in-content.html';
var source = pathname + ' ' + target;
var temp = jQuery('<div></div>');
temp.load(source, function() {
jQuery(target).replaceWith(temp.contents());
}); 

or as function

或作为功能

$.fn.replaceWithRemote = function( source, callback )   {
    var target = $(this);
    var temp = $('<div></div>');
    temp.load(source, function() {
        target.replaceWith(temp.contents());
        if (callback != null){
            callback();
        }
    });
}

$('#secondHeader').replaceWithRemote('/logged-in-content.html #secondHeader');

#9


1  

After you have loaded the content, find its children #second and unwrap it.

加载内容后,找到其子项#second并将其解包。

$("#secondHeader").children().unwrap();

#10


0  

You want to wrap in div before inserting it.

你想在插入之前包装div。

$.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);
    }
});

#11


0  

Can you add a container DIV around your "secondHeader" div? Then you'd use:

你能在“secondHeader”div周围添加一个容器DIV吗?那你就用了:

$('#secondHeaderContainer').load('/logged-in-content.html #secondHeader');

#12


-2  

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

我也有这个问题,但是我可以通过重构代码来使用.load :( 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.

所以针对孩子而不是相同的标签。

#1


41  

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

我认为最好的方法是使用get而不是load。在你的情况下你可以这样做:

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

[Edit: removed a paren]

[编辑:删除了一个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:

更新:如果/logged-in-content.html不仅仅包含您需要的代码,您可以将返回的数据包装在另一个jQuery对象中,并使用.find()来提取容器。尝试这个:

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

$( “#secondHeader”)replaceWith($(数据).find( “#secondHeader”));

#2


59  

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

你能在load()方法中改进你的选择器吗?

For example,

例如,

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

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

这样,你就不会抓住div本身,而是抓住它的内容。

#3


28  

Another way that worked best for me:

另一种最适合我的方式:

$('#div_to_replace').load('/ajax/loader', function() {
    $(this).children(':first').unwrap();
});

#4


8  

Final Answer:

最终答案:

$.fn.loadWith = function(u){var c=$(this);$.get(u,function(d){c.replaceWith(d);});};
$("#test").loadWith("somelink.html");

jQuery load adds the response INTO the element selected. jQuery's replaceWith REPLACES the selected element.

jQuery load将响应INTO添加到所选元素中。 jQuery的replaceWith替换所选元素。

<div id="curElement">start</div>

$("#curElement").load("somelink.html");
will result in:
<div id="curElement">What ever was in somelink.html</div>


$("#curElement").replaceWith("somelink.html");
will result in:
What ever was in somelink.html

I suggest adding a function to jQuery that does both:

我建议在jQuery中添加一个函数来执行这两个操作:

$.fn.loadWith = function(u){
    var c=$(this);
    $.get(u,function(d){
        c.replaceWith(d);
    });
};
$("#test").loadWith("somelink.html");

#5


3  

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

使用$ .get()为我工作,但我必须首先从响应文档中提取容器:

$.get("/page.html", function (data) {
    var elem = $(data).find('#container');
    $("#puthere").replaceWith(elem);
});

#6


2  

$.load isn't really the best choice here since that function's intended to just fill in the contents of a div, as you've seen. You can just use $.get instead and set the callback function to replace your original div, or change logged-in-content.html to exclude the div.

$ .load实际上并不是最好的选择,因为正如你所见,该函数只是用来填充div的内容。您只需使用$ .get并设置回调函数来替换原始div,或更改logged-in-content.html以排除div。

Also be aware that as a Javascript-based solution, if your users look at the source, they'll see that they can get access to logged-in-content.html by just typing it in their address bar if you're not securing it somehow else.

另请注意,作为基于Javascript的解决方案,如果您的用户查看源代码,他们会看到只要您不确保安全,只需在地址栏中键入内容即可访问logged-in-content.html不知何故。

#7


2  

I always have a jQuery function defined like this:

我总是有一个像这样定义的jQuery函数:

    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.

第二个做你想做的事。我还有一个名为loadInner的函数,它只调用load来实现它的价值。

#8


1  

var target = '#secondHeader';
var pathname = '/logged-in-content.html';
var source = pathname + ' ' + target;
var temp = jQuery('<div></div>');
temp.load(source, function() {
jQuery(target).replaceWith(temp.contents());
}); 

or as function

或作为功能

$.fn.replaceWithRemote = function( source, callback )   {
    var target = $(this);
    var temp = $('<div></div>');
    temp.load(source, function() {
        target.replaceWith(temp.contents());
        if (callback != null){
            callback();
        }
    });
}

$('#secondHeader').replaceWithRemote('/logged-in-content.html #secondHeader');

#9


1  

After you have loaded the content, find its children #second and unwrap it.

加载内容后,找到其子项#second并将其解包。

$("#secondHeader").children().unwrap();

#10


0  

You want to wrap in div before inserting it.

你想在插入之前包装div。

$.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);
    }
});

#11


0  

Can you add a container DIV around your "secondHeader" div? Then you'd use:

你能在“secondHeader”div周围添加一个容器DIV吗?那你就用了:

$('#secondHeaderContainer').load('/logged-in-content.html #secondHeader');

#12


-2  

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

我也有这个问题,但是我可以通过重构代码来使用.load :( 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.

所以针对孩子而不是相同的标签。