如何使用 jQuery.load 替换包含 div 的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1344030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:15:30  来源:igfitidea点击:

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

jquery

提问by vipergtsrz

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。

$("#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?

有任何想法吗?

采纳答案by Ali Sarchami

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]

[编辑:删除了一个括号]

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($(data).find("#secondHeader"));

回答by Funka

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 本身,而是在获取其内容。

回答by Tom Rose

Another way that worked best for me:

另一种最适合我的方法:

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

回答by Victor 'Chris' Cabral

Final Answer:

最终答案:

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

jQuery loadadds the response INTO the element selected. jQuery's replaceWithREPLACES the selected element.

jQuery加载将响应添加到所选元素中。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");

回答by DavidWainwright

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

回答by Leander Conradie

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 。

回答by Randy

$.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 $.getinstead and set the callback function to replace your original div, or change logged-in-content.html to exclude the div.

$.load 在这里并不是真正的最佳选择,因为该函数旨在填充 div 的内容,如您所见。您可以只使用$.get并设置回调函数来替换您原来的 div,或者更改 login-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 的解决方案,如果您的用户查看源代码,他们会发现如果您不保护,他们只需在地址栏中键入即可访问 login-content.html它以其他方式。

回答by key_

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');

回答by Pedro Góes

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

加载内容后,找到它的子项#second并打开它。

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

回答by Jourkey

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