jQuery .append 仅移动目标 div 的内部元素



我正在尝试通过jquery将htmldiv元素移动到页面上的不同位置,而不是复制

我目前正在尝试使用 .append 执行此操作

$('#append-options').append($('#wsite-com-product-options').html());

这段代码,功能很糟糕,给我带来了不希望的结果。第一个问题是,它只是在 #wsite-com-product-price-areadiv 内移动子内容,而不是div 本身。第二个是,这不是简单地移动元素,而是复制它们,导致移动的元素在页面上出现两次。

很明显,我对jquery相当绿色。我知道还有其他方法可以在jquery中移动元素,但我不确定哪一种是合适的。这是我在页面上使用的完整脚本,它还执行其他一些操作。

<script type="text/javascript">
(function($) {
  $(function() {
    $('#append-options').append($('#wsite-com-product-options').html());
    $('#insert-after-here').prepend($('#wsite-com-product-price-sale').html());
    $('#insert-after-here').prepend($('#wsite-com-product-price-area').html());
    var $btn = $('#wsite-com-product-buy');
    $('.wsite-product-description').first().append('<div id="something-cool"/>');
    $btn.appendTo('#something-cool').css('top', 0);
  });
})(jQuery);
</script>

不要在上面调用.html

$('#append-options').append($('#wsite-com-product-options'));
// No `.html()` here --------------------------------------^
这将移动元素

本身,包括移动其子元素。它还避免了不必要的元素到字符串然后分析回元素的往返,保留了可能附加到元素的数据和事件处理程序。

例:

$("input").on("click", function() {
  var target = $("#top").children().length ? "#bottom" : "#top";
  $(target).append($(".moveable"));
});
#top {
  width: 200px;
  height: 120px;
  border: 1px solid black;
  margin-right: 4px;
}
#bottom {
  width: 200px;
  height: 120px;
  border: 1px solid black;
}
.moveable {
  display: inline-block;
  width: 100px;
  border: 1px solid green;
}
<div>
  <div id="top"></div>
  <div id="bottom">
    <div class="moveable">
      I'm the one that moves.
      Note I have <strong>child elements</strong>
    </div>
  </div>
</div>
<input type="button" value="Click to move">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

最新更新