将div div替换为div子

时间:2017-11-06 15:03:17

标签: javascript html5

我需要帮助,如何从每个孩子div中更改父div我有html像bellow

<div id="parent1">
    <div class="toParent3">
    </div>

    <div class="toParent2">
    </div>

    <div class="toParent4">
    </div>
</div>

<div id="parent2">
     //content
</div>

<div id="parent3">
     //content
</div>

我想这样做,当我第一次加载时我只想显示#parent1及其子,然后当点击child的#parent1时,我想将整个#parent1更改为#parent2并隐藏所有div除外#parent2

2 个答案:

答案 0 :(得分:0)

您可以使用append,此代码仅适用于您的示例中的parent2。

&#13;
&#13;
$('.toParent2').click(function(){
   $('.parent2').append($('.toParent2'));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent1">
    <div class="toParent3">
      Child to parent 3
    </div>

    <div class="toParent2">
      Child to parent 2
    </div>

    <div class="toParent4">
      Child to parent 4
    </div>
</div>

<div class="parent2">
     //content
</div>

<div class="parent3">
     //content
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是一个更通用的vanilla js解决方案。

let all = document.getElementsByClassName('movable');

function hideParents() {
  Array.prototype.forEach.call(document.getElementsByClassName('_parent_'), (e) => {
    e.classList.add('hidden');
  });
}

Array.prototype.forEach.call(document.getElementsByClassName('toParent1'), (e) => {
  console.log('lols', e.addEventListener);
  e.addEventListener('click', () => {
    hideParents();
    Array.prototype.forEach.call(all, (e2) => {
      setTimeout(() => {
        const p = document.getElementById('parent1');
        p.appendChild(e2);
        p.classList.remove('hidden');
      });
    });
  });
});

Array.prototype.forEach.call(document.getElementsByClassName('toParent2'), (e) => {
  e.addEventListener('click', () => {
    hideParents();
    Array.prototype.forEach.call(all, (e2) => {
      setTimeout(() => {
        const p = document.getElementById('parent2');
        p.appendChild(e2);
        p.classList.remove('hidden');
      });
    });
  });
});

Array.prototype.forEach.call(document.getElementsByClassName('toParent3'), (e) => {
  e.addEventListener('click', () => {
    hideParents();
    Array.prototype.forEach.call(all, (e2) => {
      setTimeout(() => {
        const p = document.getElementById('parent3');
        p.appendChild(e2);
        p.classList.remove('hidden');
      });
    });
  });
});
._parent_.hidden {
  display: none;
}
<div class="_parent_" id="parent1">
  I'm parent1
    <div class="movable toParent3">To3
    </div>

    <div class="movable toParent2">To2
    </div>

    <div class="movable toParent1">To1
    </div>
</div>

<div class="_parent_ hidden" id="parent2">
     I'm parent2
</div>

<div class="_parent_ hidden" id="parent3">
     I'm parent3
</div>

不是删除setTimeout()发生了一个小故障,元素被正确移动但DOM过早刷新

here是另一种解决方案,它取代了父母的文本,而不是移动孩子。