BootstrapTable

在Web后台管理项目中对表格展示数据使用居多,主要是表格的多条件查询、分页、排序等功能。我们的项目中前端框架是Bootstrap。所以很多插件都是支持Bootstrap的。bootstrap-table是一款非常有名的开源表格插件。我们在项目中的表格就是使用它进行展示。

问题描述

在修改页面需要将之前选中的项在复选框默认选中。其实挺简单。主要是自己是后端编程,对前端了解不深。虽然有详细的文档但是也容易迷糊。

<!-- input中存放的是后台返回的‘护理项目’选中值,stirng类型 1,2,3 -->
<input type="hidden" name="nursingUuids" value="${oldPeopleNursing.nursingUuids}">
<!-- bootstrap table -->
<table id="table-beadhouseNursing" class="table table-striped table-condensed"
    data-url="beadhouseNursing/search"
    data-query-params="beadhouseNursingQueryParams">
    <thead>
    <tr>
    	<th data-checkbox="true"></th>
    	<th data-field="type">护理项目类型</th>
    	<th data-field="name">护理名称</th>
    	<th data-field="level">护理级别</th>
    	<th data-field="cost">护理费用</th>
    	<th data-field="isBase">基础护理</th>
    	<th data-field="isFeature">特色护理</th>
    </tr>
    </thead>
</table>
<script type="text/javascript">
    $(document).ready(function() {
      // 护理项目列表初始化
      $('#table-beadhouseNursing').bootstrapTable();
      $('#table-beadhouseNursing').bootstrapTable('checkBy', {field: 'uuid', values:$("input[name='nursingUuids']").val().split(",")});
    }); 
</script>

以上代码就是问题代码。感觉没错,但是复选框就是不能默认选中。

解决问题

有两个地方有问题:

  1. js执行顺序,就是$('#table-beadhouseNursing').bootstrapTable('checkBy', {field: 'uuid', values:$("input[name='nursingUuids']").val().split(",")});位置不对。
  2. checkBy中参数values值不对。

正确代码:

$('#table-beadhouseNursing').bootstrapTable({
    	  onLoadSuccess: function (data) {
    	    var nursingUuids = [];
    	    $.each($("input[name='nursingUuids']").val().split(","), function(i, n) {
    	    	nursingUuids.push(Number(n))
    	    });
    	    $('#table-beadhouseNursing').bootstrapTable('checkBy', {field: 'uuid', values:nursingUuids});
    	  }
    });

解析:
首先是需要在bootstrapTable 数据加载成功后再执行默认选中方法checkBy。然后就是values值问题,我在input中存放的值是1,2,3。checkBy的values值是数组values=[]。在使用.split(",")方法后得到的是字符串数组。所以需要进行处理与表格中uuid数据类型一致。这样checkBy方法才能找到对应的行。

更多推荐

BootstrapTable checkbox默认选中