Add element after specific list item

Jan*_*Jan 3 html javascript css jquery

I have a list of tabs set up like this. All tabs have a class tab_<number> and the active tab also has an extra class tab_active

Below these tabs there is a div that shows the dynamic content based on which tab is active

<div class="tab_content">xxx</div>

What I'm trying to do is insert the div tab_content below the active tab.

This works, but only on the second click on the tab, which I don't understand why.

The second script I tried, was looping through the different tabs and trying to insert the div like this, but this only works on the last item, because it just loops through it.

/*
// I tried two solutions, this was my first
jQuery(".tabs li").click(function() {
  jQuery(".tab_content").insertAfter(jQuery(".tab_active"));
});
*/

// second
var i;

for (i = 0; i < jQuery('.tabs li').length - 1; i++) {
  jQuery(".tab_" + i).click(function() {
    jQuery(".tab_content").insertAfter(jQuery(".tab_" + i));

  });
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tabs">
  <li class="tab_0 tab_active"><a href="#">1</a></li>
  <li class="tab_1"><a href="#">2</a></li>
  <li class="tab_2"><a href="#">3</a></li>
  <li class="tab_3"><a href="#">4</a></li>
  <li class="tab_4"><a href="#">5</a></li>
</ul>
<div class="tab_content">xxx</div>
Run Code Online (Sandbox Code Playgroud)

Can you guys/gals see what I'm doing wrong?

Much appreciated!

Har*_*cha 5

  • 这可以通过以下方式完成。
  • 但请注意,如果tab_*页面中有更多元素,则根据需要更新选择器以使其更严格,以防止选择意外元素。

$("[class^=tab_]").click(function(){
  $(this).append($(".tab_content"));
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="tabs">
    <li class="tab_0 tab_active"><a href="#">1</a></li>
    <li class="tab_1"><a href="#">2</a></li>
    <li class="tab_2"><a href="#">3</a></li>
    <li class="tab_3"><a href="#">4</a></li>
    <li class="tab_4"><a href="#">5</a></li>
</ul>

<div class="tab_content">xxx</div>
Run Code Online (Sandbox Code Playgroud)