如何从侧边栏链接导航到同一页面上的新引导4标签? [英] How to navigate to a new bootstap 4 tab on the same page from a sidebar link?

查看:123
本文介绍了如何从侧边栏链接导航到同一页面上的新引导4标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用此技术 来获取侧边栏链接,以导航至中心页面上的引导4选项卡.这是我_SidebarLayout.cshtml中的javascript:

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>

侧边栏锚链接到该页面,并向我要导航到的选项卡的href中添加一个片段(哈希)(网址末尾:SPC#SpcFilm).侧边栏链接也调用上述函数.

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>

在Index.cshtml上,引导4"选项卡由href="#SpcFilm"标识.此解决方案在导航到新页面时有效,但在导航至同一页面上的另一个选项卡时不起作用.

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.

推荐答案

在同事的帮助下,我在这里回答自己的问题.使用现代浏览器(由jQuery识别)的hashchange事件选择选项卡.在Bootstrap 4中,使用data-toggle="tab"data-toggle="pill"激活选项卡.因此,唯一需要的脚本是:

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>

每个侧边栏链接都包含与所需标签的href匹配的哈希.单击侧边栏链接时,上面的jQuery触发对选项卡的单击,从而打开页面上的选项卡.

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.

注意:请确保从侧边栏链接中删除onclick="selectTabNamedInUrlHash();"并删除相应的功能,因为它不再需要,并且可能会干扰解决方案.

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.

这篇关于如何从侧边栏链接导航到同一页面上的新引导4标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆