I had a problem about the active tab.I use .append() to built tabs and I don't use href to connect data of tab.
when I click tab .console log() to show the text of the active tab.
My problem is when I clicked tab 2 the text of the active tab still is tab 1.
I have to clicked tab 2 again the active tab gonna change to tab 2. I don't see anyone who has the same problem so wish someone can help me. Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Dynamic Tabs</h2>
<ul class="nav nav-tabs">
</ul>
</div>
<script>
$(document).ready(function(){
for(i = 1;i <= 2 ; i++){
renewid='tab_'+i;
if(i == 1){
$('.nav-tabs').append("<li class='active'><a data-toggle='tab' id=" + renewid + ">Chart"+ [i] +"</a></li>");
}
else{
$('.nav-tabs').append("<li><a data-toggle='tab' id=" + renewid + ">Chart"+ [i] +"</a></li>");
}
};
$(".nav-tabs a").click(function(){
alert('set_active = ' + $('.nav-tabs .active').text());
});
});
</script>
</body>
</html>
Use shown.bs.tab
event instead of click
.
$(".nav-tabs a").on('shown.bs.tab', function () {
alert('set_active = ' + $('.nav-tabs .active').text());
});
You just need to apply 'addClass' method at the time of click event,that you can see in below snippet :
$(document).ready(function(){ for(i = 1;i <= 2 ; i++){ renewid='tab_'+i; if(i == 1){ $('.nav-tabs').append("<li><a data-toggle='tab' id=" + renewid + ">Chart"+ [i] +"</a></li>"); } else{ $('.nav-tabs').append("<li><a data-toggle='tab' id=" + renewid + ">Chart"+ [i] +"</a></li>"); } }; $(".nav-tabs a").click(function(){ $('.nav-tabs').find('li').removeClass('active'); $(this).closest('li').addClass('active') alert('set_active = ' + $('.nav-tabs .active').text()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <h2>Dynamic Tabs</h2> <ul class="nav nav-tabs"> </ul> </div>
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.