Spring Boot2+Thymeleaf+Bootstrap4首次激活标签页shown事件未触发
shown.bs.tab Event Not Triggering on Initial Active Tab I totally get this frustration—Bootstrap tabs have a little quirk here! The shown.bs.tab event only fires when a tab is activated after the page loads (either via user click or programmatic switch), not for the tab that’s already marked as active when the page first renders. Let’s fix this step by step.
First, let’s assume your tab structure looks something like this (based on your snippet):
<ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" id="tab1-tab" data-toggle="tab" href="#tab1">Tab 1</a> </li> <li class="nav-item"> <a class="nav-link active" id="tab2-tab" data-toggle="tab" href="#tab2">Tab 2</a> <!-- Your initial active tab --> </li> </ul> <div class="tab-content"> <div class="tab-pane fade" id="tab1">Content for Tab 1</div> <div class="tab-pane fade show active" id="tab2">Content for Tab 2</div> </div>
And your existing JavaScript probably looks like this (where the event doesn’t fire on page load):
$(document).ready(function() { $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var targetTab = $(e.target).attr("href"); // Your custom logic here (e.g., load data, initialize components) console.log("Active tab: " + targetTab); }); });
Solution 1: Manually Trigger the Event for the Initial Active Tab
The simplest fix is to explicitly fire the shown.bs.tab event on the pre-active tab once the DOM is ready. Add this line inside your document.ready function:
$(document).ready(function() { // Existing event handler $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var targetTab = $(e.target).attr("href"); console.log("Active tab: " + targetTab); // Your logic here }); // Trigger event for the initially active tab $('.nav-tabs .nav-link.active').trigger('shown.bs.tab'); });
Solution 2: Reusable Function (Cleaner for Complex Logic)
If your tab-specific logic is more involved, extract it into a reusable function. This avoids code duplication and ensures your initial tab gets the same treatment as switched tabs:
$(document).ready(function() { // Reusable function to handle tab-specific tasks function handleTabActivation(tabId) { console.log("Processing tab: " + tabId); // Add your logic here (e.g., fetch data, initialize charts, etc.) } // Bind function to tab shown event $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) { var targetTab = $(e.target).attr("href"); handleTabActivation(targetTab); }); // Run function for the initial active tab var initialActiveTab = $('.nav-tabs .nav-link.active').attr('href'); handleTabActivation(initialActiveTab); });
Just double-check that jQuery is loaded before Bootstrap’s JS (since Bootstrap tabs depend on jQuery) and that your script runs after the DOM is fully loaded. That should get your initial tab’s event firing as expected!
内容的提问来源于stack exchange,提问作者robert trudel

