问题
I'm unable to get sidebar links to navigate to bootstrap 4 tabs on the center page using this technique. Here is the javascript in my _SidebarLayout.cshtml
:
<script>
function selectTabNamedInUrlHash() {
let selectedTab = window.location.hash;
$('.nav-link[href="' + selectedTab + '"]').trigger('click');
}
jQuery(document).ready(function ($) {
selectTabNamedInUrlHash();
})
</script>
A sidebar anchor links to the page and adds a fragment (hash) to the href of the tab I want to navigate to (url end: SPC#SpcFilm). The sidebar link also calls the above function.
<a onclick="selectTabNamedInUrlHash();" asp-page="/SPC/Index" asp-fragment="SpcFilm">Film</a>
On Index.cshtml the Bootstrap 4 tab is identified by href="#SpcFilm"
This solution works when navigating to a new page, but it's not working when navigating to another tab on the same page.
回答1:
I'm answering my own question here with the help of a coworker. Use the hashchange event of modern browsers (which is recognized by jQuery) to select the tab. In Bootstrap 4 tabs are activated using data-toggle="tab"
or data-toggle="pill"
. So the only script needed is:
<script>
$(window).on('hashchange ready', function () {
let selectedTab = window.location.hash;
$('a[href="' + selectedTab + '"][data-toggle="tab"]').trigger('click');
});
</script>
Each sidebar link contains a hash matching a desired tab's href. When the sidebar link is clicked the jQuery above triggers a click on the tab thus opening the tab on the page.
Note: Be sure to remove onclick="selectTabNamedInUrlHash();"
from the sidebar links and remove the corresponding function as it is no longer needed and may interfere with the solution.
来源:https://stackoverflow.com/questions/60097441/how-to-navigate-to-a-new-bootstap-4-tab-on-the-same-page-from-a-sidebar-link