1

複数のセクションがあります...これらのセクション内には子要素がほとんどありません...セクションごとに1つの要素(たとえば.inner)を別の要素(h1など)の後に移動するように操作する必要があります

私の試みはここhttp://jsfiddle.net/shavindra/LDpwq/1/ですが、問題はループスルーせず、最後にうまく印刷されないことです。しかし、以下に示すように出力を変えたいのですが...

初期状態:

<section class="greeting">
  <h2>Greetings 1</h2>
  <div class="time">Morning</div>
  <div class="inner">Good 1</div>
</section>

<br />
<br />

<section class="greeting">
  <h2>Greetings 1</h2>
  <div class="time">Afternoon</div>
  <div class="inner">Good 2</div>
</section>

<br />
<br />

<section class="greeting">
  <h2>Greetings 1</h2>
  <div class="time">night</div>
  <div class="inner">Good 3</div>
</section>

操作後

<section class="greeting">
  <h2>Greetings 1</h2>
  <div class="inner">Good 1</div>
  <div class="time">Morning</div>
</section>

<br />
<br />

<section class="greeting">
  <h2>Greetings 1</h2>
  <div class="inner">Good 2</div>
  <div class="time">Afternoon</div>
</section>

<br />
<br />

<section class="greeting">
  <h2>Greetings 1</h2>
  <div class="inner">Good 3</div>
  <div class="time">night</div>
</section>
4

3 に答える 3

1

元のコードには2つの問題がありました。

$(".greeting").each(function() {
    $(this).children('.time').addClass("on");
    $(this).children('.time').after($('.inner'));
});

1)inner移動するクラスを持つすべての要素を選択しています:

$('.inner')

代わりに、現在のdivにあるものだけを使用してください。

$(this).children('.inner')

2)関数を使用しています。この関数は、関数を呼び出す要素の後にafter、パラメーターとして渡されたコンテンツを挿入します。一方、逆の方法で動作します。jQueryドキュメントから:insertAfter

.after()を使用すると、メソッドの前にあるセレクター式は、コンテンツが挿入された後のコンテナーになります。一方、.insertAfter()を使用すると、コンテンツは、セレクター式またはオンザフライで作成されたマークアップとしてメソッドの前に配置され、ターゲットコンテナの後に挿入されます。

したがって、コードを次のように変更できます。

$(".greeting").each(function() {
    $(this).children('.time').addClass("on");
    $(this).children('.time').insertAfter($(this).children('.inner'));
});

またはこれ:

$(".greeting").each(function() {
    $(this).children('.time').addClass("on");
    $(this).children('.inner').after($(this).children('.time'));
});
于 2012-05-14T00:20:54.920 に答える
1
$(".time").each(function() {
    $(this).before($(this).siblings('.inner'));
});​

デモ:http: //jsfiddle.net/LDpwq/4/

于 2012-05-14T00:01:26.417 に答える
0

これを試して:

$(".greeting").each(function() {
    $(this).children('div:eq(0)').before($(this).children('div:eq(1)'));
});

http://jsfiddle.net/LDpwq/15/

于 2012-05-14T00:01:00.547 に答える