选择与dataTable上的标题关联的列

时间:2013-06-20 19:56:56

标签: jquery jsf-2 primefaces

每当用户点击<th>时,我都会被要求突出显示与某个<th>相关联的列。所有这些都在 PrimeFaces <p:dataTable>

我能想到的最简单的方法是用JQuery来做这件事,所以我开始研究,偶然发现了这个答案here

在那里, BalusC 提供了一段我能够为自己的用例编辑的代码,我最终得到了这个:

$(document).ready(function () {
    $('#mainForm\\:table th').click(function () {

        var th = $(this);
        var index = $('th', th.parents('tr')).index(th);
        var column = $('tbody td:nth-child(' + (index + 1) + ')', th.parents('table'));
        column.addClass('light-grey');
    });
});

这段代码实际上对我有用。但有一点我无法弄清楚。

只要将light-grey类添加到列中,它就会被删除。我不知道它是否与JSF的生命周期有关,或者与我不知道的渲染时间有关。

所以我得到的结果是列闪烁变为灰色并且返回非常快。

有谁知道为什么会这样?


编辑1

这是我的xhtml

<h:form id="mainForm">
    <p:dataTable id="table" value="#{myManagedBean.items}" var="item"
        sortBy="#{item.value2}">

        <p:column headerText="Value 1" sortBy="#{item.value1}">
            <h:outputText value="#{item.value1}" />
        </p:column>

        <p:column headerText="Value 2" sortBy="#{item.value2}">
            <h:outputText value="#{item.value2}" />
        </p:column>

        <p:column headerText="Value 3" sortBy="#{item.value3}">
            <h:outputText value="#{item.value3}" />
        </p:column>

    </p:dataTable>
</h:form>

我创建了一个小项目来隔离问题,上面的表格是我用于测试的表格。

是的,只要我点击标题来改变排序,就会触发AJAX请求。我查看了Chrome调试器的“网络”标签。

1 个答案:

答案 0 :(得分:0)

通过 @ MaQy 评论,我得出了一个解决方案,最终的JQuery代码如下所示:

$(document).ready(function () {
    function afterLoad(){
        var th = $('.ui-datatable table th.ui-state-active');
        var index = $('th', th.parents('tr')).index(th);
        var column = $('tbody td:nth-child(' + (index + 1) + ')', th.parents('.ui-datatable'));
        column.addClass('light-grey');
    }

    $('body').bind('ajaxComplete', function(e, xhr, settings){
        afterLoad();
    });

    // Invoking afterLoad() for the first time 
    // to load the table already highlighted.
    afterLoad();
});

ui-state-active是PrimeFaces添加到所选<th>的类,因此可以让事情变得更容易。

如果您对此解决方案有任何建议,改进或投诉,请发表评论。在我对JQuery的一点知识中,这就是我能想到的所有内容。

相关问题