如何使 PrimeFaces 选项卡“可链接”?

2024-03-07

我希望能够链接到 PrimeFaces 的“tabView”中的各个选项卡。换句话说,如果我的页面“test.jsf”有一个带有标题为“Example”的选项卡的 tabView,我希望能够单击“Test.jsf#Example”的链接并自动加载“Example”选项卡。我怎样才能做到这一点?


这可以通过一点点 JavaScript 来完成(使用 jQuery)。我希望我对以下代码的注释足够好,以便可以理解。

<script type="text/javascript">
//    What this does: when the page is loaded with a URL fragment (i.e, the #abc in example.com/index.html#abc),
//    load the tab (by "clicking" on the link) that has the same text value as the fragment.
//    Example: if you go to test.jsf#Example, the tab called "Example" will be clicked and loaded.
//    This allows individual tabs to be linked to, and puts what tab you were on in the history.
    navigateToTab = function () {
        if (window.location.hash) {
            jQuery('ul.ui-tabs-nav li a').each(function (i, el) {
                if (jQuery(el).text() === window.location.hash.replace('#', '')) {
                    jQuery(el).click();
                    return;
                }
            })
        }
    };

    jQuery().ready(navigateToTab);
    jQuery(window).bind('hashchange', navigateToTab);

//    This makes it so that if you click a tab, it sets the URL fragment to be the tab's title. See above.
//    E.g. if you click on the tab called "Example", then it sets the onclick attribute of the tab's "a" tag
//    to be "#Example"
    setupTabFragmentLinks = function () {
        jQuery('ul.ui-tabs-nav li a').each(function (i, el) {
            el.onclick = function() {window.location = '#' + jQuery(el).text()};
        })
    };
    jQuery().ready(setupTabFragmentLinks);
</script>

您所要做的就是将该 JavaScript 插入具有选项卡的页面中。然后你可以通过通常的方式获得一个选项卡的链接<a href='test.jsf#Example>Click here!</a>。另一个好处是,您所在的选项卡将成为浏览器历史记录的一部分;也就是说,如果您离开具有选项卡的页面,然后按“后退”按钮,您将返回到您所在的选项卡。

注意:如果 tabView 发生变化(例如添加或删除选项卡),则需要再次调用 setupTabFragmentLinks。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使 PrimeFaces 选项卡“可链接”? 的相关文章