在看【江苏职卫】专业技术人员考核抽取查询功能模块时,发现添加人员时只能在第一列的复选框勾选或取消,现想实现单击行勾选或取消,观察文档后,实现代码如下:
<p:dataTable var="itm" value="#{mgrbean.psnInfoObjectList}" id="psnDataTable" paginator="true" rows="10" emptyMessage="没有数据!" paginatorPosition="bottom" pageLinks="5"
selection="#{mgrbean.selectedPsnInfoObjectList}" rowKey="#{itm[0]}" rowSelectMode="add">
<p:column selectionMode="multiple"/>
<p:column style="width: 80px;text-align: center;" headerText="姓名">
<h:outputText value="#{itm[1]}" />
</p:column>
<p:column style="width: 60px;text-align: center" headerText="性别">
<h:outputText value="#{itm[2]}" />
</p:column>
<p:column style="width: 100px;text-align: center" headerText="出生年月"> <h:outputText value="#{itm[3]}" />
</p:column>
<p:column style="width: 100px;text-align: center" headerText="手机号码">
<h:outputText value="#{itm[6]}" style="color: red;" rendered="#{false == itm[8]}" />
<h:outputText value="#{itm[6]}" rendered="#{itm[8]}" />
</p:column>
<p:column style="width: 100px;text-align: center" headerText="职称">
<h:outputText value="#{itm[4]}" />
</p:column>
<p:column style="padding-left:3px;" headerText="资质类别">
<h:outputText value="#{itm[5]}" />
</p:column>
</p:dataTable>
在指定了selection以及rowKey后,rowSelectMode需指定为"add",该属性默认是"new",即选中行时会清除掉之前的选中项,指定为"add"后则会保留之前的选中项,文档说明为:
Use rowSelectMode option to customize the default behavior on row click of a multiple
selection enabled datatable. Default value is "new" that clears previous selections and "add"
mode keeps previous selections same as selecting a row with mouse click when metakey is on.
使用后发现问题:单击行选中,二次单击不会取消
查看datatable.js源代码后发现,需要按下Ctrl键或Win键再单击行,则会取消选中行,源码如下:
研究后发现,若要实现单击行选中,再单击选中行取消,可以在页面中重写DataTable的onRowClick方法,将if (c && f ) 修改为 if( c ) 即可,代码如下:
<script type="text/javascript">
//<![CDATA[
PrimeFaces.widget.DataTable.prototype.onRowClick = function(e, d, a) {
if ($(e.target).is("td,span:not(.ui-c)")) {
var g = $(d)
, c = g.hasClass("ui-state-highlight")
, f = e.metaKey || e.ctrlKey
, b = e.shiftKey;
if (c) {
this.unselectRow(g, a)
} else {
if (this.isSingleSelection() || (this.isMultipleSelection() && e && !f && !b && this.cfg.rowSelectMode === "new")) {
this.unselectAllRows()
}
if (this.isMultipleSelection() && e && e.shiftKey) {
this.selectRowsInRange(g)
} else {
this.originRowIndex = g.index();
this.cursorIndex = null;
this.selectRow(g, a)
}
}
PrimeFaces.clearSelection()
}
}
//]]>
</script>