我做了很多搜索,但我觉得答案可能很简单。
我拥有的: jQuery 从 div 中获取列表项并将它们推送到数组中以附加到其他位置。
发生了什么:对象被推送到数组,但它们也从 DOM 中删除。
我需要什么:将它们推送到数组,但也将原始文件保留在原来的位置。
这是我用来引用的代码
var leftItems = [];
var rightItems = [];
$('.footer-top li').slice(0,6).each(function(i) {
leftItems.push(this);
});
$('.footer-top li').each(function(i) {
rightItems.push(this);
});
$.each(rightItems, function(index, value) {
$('.footer-menu-mob ul.right').append(this);
});
$.each(leftItems, function(index, value) {
$('.footer-menu-mob ul.left').append(this);
});
最佳答案
给定对象一次只能位于 DOM 中的一个位置。因此,当您.append()
数组中的项目时,您将它们移动到 DOM 中的新位置。如果您想在新位置获取这些项目的副本,则可以使用 jQuery 的 .clone()
。
请参阅下面的注释以了解发生的情况:
var leftItems = [];
var rightItems = [];
// this makes a nice array of DOM elements, nothing is removed from
// the DOM here
$('.footer-top li').slice(0,6).each(function(i) {
leftItems.push(this);
});
// this makes a nice array of DOM elements, nothing is removed from
// the DOM here
$('.footer-top li').each(function(i) {
rightItems.push(this);
});
// this MOVES these elements from their current location in the DOM to
// a new location
$.each(rightItems, function(index, value) {
$('.footer-menu-mob ul.right').append(this);
});
// this MOVES these elements from their current location in the DOM to
// a new location
$.each(leftItems, function(index, value) {
$('.footer-menu-mob ul.left').append(this);
});
<小时/>
如果你不需要保留数组,那么你可以使用.clone()
并简化你的代码,如下所示:
$('.footer-top li').slice(0,6).clone().appendTo('.footer-menu-mob ul.left');
$('.footer-top li').clone().appendTo('.footer-menu-mob ul.right');
关于jquery - 将对象推送到数组而不从 DOM 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24419365/