【问题标题】:How to make a child the parent of it's parent using jQuery? [closed]如何使用 jQuery 让孩子成为其父母的父母? [关闭]
【发布时间】:2015-10-15 06:48:53
【问题描述】:

我有这个

<div class="a" foo="bar">
  <div class="b">
    <!-- various things here -->
  </div>
</div>

我想把它变成这样:

<div class="b">
  <div class="a" foo="bar">
    <!-- various things here -->
  </div>
</div>

使用 jQuery。我该怎么做?

【问题讨论】:

  • stackoverflow.com/help/how-to-ask - 先前研究和努力的迹象是 SO 指南的绝对要求。 SO 适用于已经研究和试验但仍无法解决的特定编程问题,不是教程的替代品。查找任何 jquery 教程并首先执行此操作,然后如果仍然有问题,则搜索“jquery 更改父级”或类似内容 - 绝对不需要也不适合像这样的另一个非研究主题。

标签: javascript jquery html


【解决方案1】:

要保留events 和处理程序,请使用clone()

$(function () {
  a = $(".a").clone();
  a.find(".b").remove().end().html($(".b").html());
  $(".b").unwrap().html("").append(a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="a" foo="bar">
  <div class="b">
    <!-- various things here -->
  </div>
</div>

【讨论】:

  • @charlietfl 再检查一次?我已经更新了代码。
  • 这对我不起作用;我将内容作为b 的孩子,a 作为另一个孩子,例如在带有 jquery 1.9.1 的 firefox 41 上的 &lt;div class="b"&gt;&lt;!--various things here--&gt; &lt;div class="a" foo="bar"&gt;&lt;/div&gt;&lt;/div&gt;
  • @Shel Right...让我纠正它。
  • @Shel 现在可以工作了。看看吧。
【解决方案2】:

除了显示的 html 之外没有任何特定标准可以做到:

$('.a').html( $('.b').html()).wrap('<div class="b">');

DEMO

【讨论】:

  • 这在技术上是正确的……最好的正确方法(但 Praveen 仍然得到公认的答案)。
【解决方案3】:

如下使用...

$('.b').insertBefore($('.a'));
$('.b').append($('.a'));

【讨论】:

  • 在 .html('') 中,您可以传递一个包含附加 html 代码的变量
  • 我投票太快了;这不起作用。
  • 对不起,我弄错了,现在我改了。它会完全按照您想要的方式工作。
  • 你有没有错误就标记,正确就标记的习惯?
  • 不,你的回答还是不行;我恢复了我错误的赞成票。见这里:jsfiddle.net/r14fga48
猜你喜欢
  • 1970-01-01
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2011-08-31
相关资源
最近更新 更多