Addelementafterspecificlistitem

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>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));

  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
  <li><a href="#">5</a></li>
</ul>
<div>xxx</div>

回答

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

$("[class^=tab_]").click(function(){
  $(this).append($(".tab_content"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li><a href="#">1</a></li>
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
    <li><a href="#">4</a></li>
    <li><a href="#">5</a></li>
</ul>

<div>xxx</div>


以上是Addelementafterspecificlistitem的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>