【问题标题】:Push objects to array without removing from DOM将对象推送到数组而不从 DOM 中删除
【发布时间】:2014-06-26 06:23:46
【问题描述】:

我做了很多搜索,但我觉得答案可能很简单。

我有什么: 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);
  });

【问题讨论】:

  • 你可以试试.push($(this).clone());

标签: jquery html arrays


【解决方案1】:

给定对象一次只能是 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');

【讨论】:

    【解决方案2】:

    您需要克隆 DOM 元素。您还可以大大简化您的代码:

    $('.footer-top li').each(function(index, value) {
        var targetSelector = '.footer-menu-mob ul.right';
        if(index > 6) {
            targetSelector = '.footer-menu-mob ul.left';
        }   
        $(this).clone().appendTo(targetSelector);
    });
    

    请注意,这里我假设您希望将前 7 个 li 项目附加到 .footer-menu-mob ul.right,其余的附加到 .footer-menu-mob ul.left,而您原来的切片数组方法将前 7 个元素放在右边,所有元素在左边。由于您重新指定了选择器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-03
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      相关资源
      最近更新 更多