如何使用jQuery.load替换包括div的div [英] How can I use jQuery.load to replace a div including the div
问题描述
我有一个id为"secondHeader"的div,我想用另一个具有相同id为"secondHeader"的div替换整个div,但不是替换它,而是仅将加载的div添加到第一个div中.
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.
$("#secondHeader").load("/logged-in-content.html #secondHeader");
这就是发生的事情...
This is what happens...
<div id="secondHeader"><div id="secondHeader"></div></div>
我想发生的是ajax加载中的secondHeader div,以完全替换初始页面中的secondHeader.
What I want to happen is the secondHeader div from the ajax load to totally replace the secondHeader in the initial page.
我知道这听起来很愚蠢,但这是我要完成的工作...当用户未登录时,他们会看到未登录的标头.我正在使用ajax允许该人登录该站点,并且我想通过ajax将未登录的标头替换为已登录的标头.
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.
我已经尝试了所有我知道的东西,例如...
I have tried everything I know such as...
$("#secondHeader").replaceWith($("#secondHeader").load("/logged-in-content.html #secondHeader"));
...并在手之前使用.remove()...
...and using .remove() before hand...
有什么想法吗?
推荐答案
我认为最好的方法是使用get而不是load.在您的情况下,您可以这样做:
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);
});
更新: 如果/logged-in-content.html除了所需的代码以外,还可以将返回的数据包装在另一个jQuery对象中,然后使用.find()提取容器. 试试这个:
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"));
$("#secondHeader").replaceWith($(data).find("#secondHeader"));
这篇关于如何使用jQuery.load替换包括div的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!