我正在尝试从具有 id ajax-container 的 div 复制所有内容到另一个具有 newContent 类的 div 中。 我已经尝试过使用:删除原始内容的前置、追加和 html,克隆功能不起作用。
$(".newContent").html($("#ajax-container")).html();
$('.newContent').prepend($('#ajax-container'));
那些正在删除原来的div
clone方法不是复制页面的所有内容,只复制第一个div。 我想复制那个 div 中的所有内容。 我在这里发现了一些问题,但没有帮助。
$('#ajax-container').clone().appendTo('.newContent');
这只放了parrent div,不是全部放在里面
var $comt=$("#ajax-container").children().clone(true,true);
$(".newContent").html($comt).html();
这根本行不通
newContent
div 位于 wordpress 主题中的 page.php 中,根位置使用下划线,ajax-container
位于标题部分。通过 ajax 加载的 ajax 容器 div 的内容。
<section class="viewport" id="content">
<div class="right">
<div class="front" id="ajax-container" ></div>
...
</div>
</section>
这是 jquery 文件:
$(document).ready(function(){
$("ul.nav-menu> li a").on('click',function(e){
e.preventDefault();//stop loading the new link
// e.stopPropagation();
var url = this.href;
$('ul.nav-menu> li a.current').removeClass('current');
$(this).addClass('current');
$("#primary.content-area").remove();//remove old content
$.ajax({
url: url,
type: "GET",
dataType: "html",
success: function (res) {
$("#ajax-container").html($(res).find("#primary.content-area")
.addClass('done'))
.fadeIn('slow');
}
});
//var amount =360;
//$("#ajax-container").clone().insertAfter("header#masthead.site-header");
//var $comt=$("#ajax-container").children().clone(true,true);
//$(".newContent").html($("#ajax-container")).html();
//$('.newContent').prepend($('#ajax-container'));
//$('#ajax-container').clone().appendTo('.newContent');
// $(".newContent").html($("#ajax-container").html());
var getContent = $('#ajax-container').html();
$('.newContainer').append(getContent);
});
});
我用的是wordpress,消失的内容是用ajax加起来的。我已经在上面发布了 jquery 文件。
$('div#ajax-container.front.PageLandingFront').clone().appendTo($('div#primary.content-area'));
此行进行复制,但目标 div 中没有所有 html,只有根 div 元素。有什么想法吗?
我终于解决了,这就是我做错的地方:
$.ajax({
url: url,
type: "GET",
dataType: "html",
success: function (res) {
$("#ajax-container").html($(res).find("#primary.content-area").addClass('done')).fadeIn('slow');
},
complete: function () {
$('div#ajax-container.front.PageLandingFront').children().clone().appendTo($('div#primary.content-area'));
$('div#ajax-container.front.PageLandingFront').html("");
}
})
似乎我有这个错误是因为 ajax 函数与我的克隆同时加载,所以我必须确保在我想克隆那个 div 时完成 ajax 调用。感谢您的支持! 这个话题可以关闭了,因为我的问题已经解决了!
最佳答案
根据 jQuery API 的规范,clone
方法创建给定元素的深度克隆,包括元素本身。如果您需要元素本身,请选择以下三个之一:
$('.newContent').append($('#ajax-container').clone());
$('#ajax-container').clone().appendTo('.newContent');
$('#ajax-container').clone().appendTo($('.newContent'));
如果您只想要给定元素内的子元素,您可以使用其中的一个。
$('.newContent').append($('#ajax-container').children().clone());
$('#ajax-container').children().clone().appendTo('.newContent');
$('#ajax-container').children().clone().appendTo($('.newContent'));
关于javascript - .prepend() .append() 正在删除原来的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350326/