2

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

4

2 回答 2

3

这可以用一点点 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。

于 2013-01-08T19:35:30.263 回答
1

Primefaces 为<p:tabView/>(和许多其他组件)提供了一个 javascript API。select(index)您可以在您的客户端widgetVar名称上调用该方法<p:tabView/>。例如,在选项卡视图上

 <p:tabView id="thePanel"  widgetVar="tabPanel"/>

从 a<p:CommandButton/>中,您可以调用属性tabPanel.select(1)onclick选择第一个选项卡,依此类推

 <p:commandButton update=":thePanel" value="Do It " id="doIt" onclick="tabPanel.select(1)"/>
于 2013-01-10T00:50:58.940 回答