-1

私はいくつかの要素を jQuery で li 要素にラップしようとしています。私の問題は、それらがli内にある順序を切り替えたいということです。今はli開始a---終了ですが、私は開始---div終了liしたいです。lidivali

これどうやってするの?私はすべてを試しましたが、うまくいきませんでした。これが私の現在のコードです:

$('a.top_link+div.sub').not(":first").each(function() {
  $(this).prev().andSelf().wrapAll('<li class="aaa">');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="something.com" class="top_link">Something</a>
<div class="sub">Some other content..</div>

それをラップして、コンテンツを次のように並べ替えます。

<li class="aaa">
  <div class="sub">Some other content..</div>
  <a href="something.com" class="top_link">Something</a>
</li>

上記の要素は複数あり、内容のみが異なります (メニューの一部)。

4

1 に答える 1

1

This should work:

$('a.top_link+div.sub').each(function () {
    $(this).insertBefore($(this).prev()).add($(this).next()).wrapAll('<li class="aaa">');
});

For each div.sub, the above code does:

  1. Move it to before the <a>
  2. Add the <a> to the collection
  3. Wrap both in an <li>

Demo: http://jsfiddle.net/vjC3x/

于 2013-07-10T11:53:06.780 に答える