简体   繁体   中英

Dynamically adding a tab in bootstrap doesn't show tab-pane content after navigating away and back

Ive seen a lot of similar questions, but nothing that is quite like this (that I can find).

This is in a rails 5 app, bootstrap-sass 3.3, jquery 1.12.4.

$("#opendata").on("click", function(){
  $("<div class='tab-pane active' id='summary'>hi</div>").appendTo("#tab-content");
  $("<li class='active' data-toggle='tab'><a href='summary' aria-expanded='true'>Summary</a></li>").appendTo("#tabs")
 })

I have 2 tabs that are loaded with the page, and need to add other tabs dynamically. The above code works - the tab is added, and the tab-pane contents are displayed. However if I navigate away from that tab, and navigate back (the tab itself will go active) the tab-pane is showing the contents of the previous tab.

I've narrowed the issue down to the dynamic tab-pane not getting an 'active' class put on it. I've tried to do this via console as well, and it doesn't work either.

The main solution I saw for dynamic tabs was to add something like this

jQuery(function($){
  $("tabs").on("click", "a", function(e){
    e.preventDefault();
    $(this).tab('show');
  })
})

But to no avail. It seems like the added tab-pane just doesn't respond to anything, console or otherwise. Am I missing something or going about this the wrong way? The tab gets added fine, just when navigating away and back that it doesn't respond.

so chalk this one up to looking at the same code for too long on my part. The solution is:

$("<li class='active' data-toggle='tab'><a href='#summary' aria-expanded='true'>Summary</a></li>").appendTo("#tabs")

Notice the '#' in front of the href that I forgot in the first post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM