【问题标题】:Switching the order of multiple sets of elements with jQuery用jQuery切换多组元素的顺序
【发布时间】:2013-05-17 13:01:58
【问题描述】:

我在页面上有许多元素,其中包含标题和图像,我想更改它们的顺序。例如用 h2 切换 img 的顺序:

<section>
  <img>
  <h2></h2>
</section>

我有该部分的多个实例,因此尝试依次迭代每个实例:

$("section h2").each(function(){
    $(this).before($(this).prev('img'));    
});

但这没有任何效果。谁能建议我做错了什么?

【问题讨论】:

  • 你能发个小提琴吗?很可能,一旦你添加了新的,你就不会 remove()ing 旧的了
  • 来自 docs Insert content, specified by the parameter, before each element in the set of matched elements. 所以你在此之前插入了 img - 这就是它不会改变的原因
  • 感谢@JoeCoderGuy,但下面 VisioN 的回答解决了它。我的小提琴在jsfiddle.net/DhCDp 供任何感兴趣的人使用。

标签: javascript jquery switch-statement swap


【解决方案1】:

insertBefore() 将完美运行:

$("section h2").each(function() {
    $(this).insertBefore($(this).prev("img"));
});

演示: http://jsfiddle.net/kqLeD/

【讨论】:

  • 完美,谢谢。我对 .before() 和 .insertBefore() 的混淆
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多