【问题标题】:Detach object content from DOM, add other and then append to DOM从 DOM 中分离对象内容,添加其他内容,然后附加到 DOM
【发布时间】:2017-01-08 16:23:21
【问题描述】:

我有这个:

div#origin
   span
   span

div#final

我需要从“origin”中分离内容,添加一些额外的跨度,然后使用 jQuery 将所有内容附加到“final”。

我怎么能做到这一点。我正在搜索,但也许我用了错误的术语,因为我没有得到答案。

感谢任何进一步的帮助。

【问题讨论】:

  • 所以你需要removeaddappend
  • @Jaromanda,所有这些都在同一顺序。 :-)

标签: javascript jquery dom append detach


【解决方案1】:

您可以使用 append 将子元素和新定义的元素移动到它们的新父元素:

JS Fiddle

var children = $('#origin').children();
var extra = '<span class="extra">Extra Stuff</span>';

// This will move the children to the new parent and add the extra variable defined
$('#final').append(children, extra); 

根据您的需要可能会增加更多灵活性的另一个选项是克隆子代并在需要时附加它:

JS Fiddle - clone() and append()

var children = $('#origin').children();
var cloned = children.clone(true,true); // Store a copy of the children to be appended
var extra = '<span class="extra">Extra Stuff</span>';

children.remove(); // Remove the old non-cloned children
$('#final').append(cloned, extra); // append cloned and extra elements

【讨论】:

  • “孩子们”拯救我的一天。谢谢@Derek Story,这就是我的答案。 :-)
【解决方案2】:

这应该可以解决问题:

var data1 = $("#span1").text(),
  data2 = $("#span2").text(),
  other = "Whatever else you wanted"
$("#span1").remove()
$("#span2").remove()
$("#final").append("<span>" + data1 + "</span>")
$("#final").append("<span>" + data2 + "</span>")
$("#final").append("<span>" + other + "</span>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="orgin">
  <span id="span1">span</span>
  <span id="span2">span</span>
</div>

<div id="final">
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2023-03-16
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2016-09-26
    相关资源
    最近更新 更多