在加载数据之后需要先格式化再渲染,格式化四种数据:
<script id="bdt_list" type="text/html">
<div class="row col-xs-12">
<div class="box box-body table-responsive no-padding">
<table id="tb_list" class="table table-striped dataTable">
<thead>
<tr>
<%for(var item_title in wordbook){ %>
<% var title = getTitle(wordbook[item_title]); %>
<th width="auto"><%:=title; %></th>
<%}%>
</tr>
</thead>
<tbody id="tb_tbody">
<%if(data!=null&&data.length>0){%>
<%for(var i=0;i<data.length;i++){%>
<% var item = data[i]; %>
<tr data-index="<%=i%>" >
<%for(var item_title in wordbook){ %>
<% var rule = getRule(wordbook[item_title]); %>
<td style="word-break: break-all;"><%:=formatN(item[item_title],rule); %></td>
<%}%>
</tr>
<%}}%>
</tbody>
</table>
</div>
</div>
</script>
// 展示搜索返回的数据
showList: function(ret) {
var that = this;
var listData = JSON.parse(ret);
var bt = baidu.template;
var chtml = bt('bdt_list', listData.data);
$('#div_loading').hide();
$('#div_list').html(chtml);
/*
* 格式化数据开始
*/
/* 通用格式化,number:传入的值 rule:规则 */
formatN: function(number, rule) {
var number = number.toString();
if (!isNaN(number)) {
if (rule == 1) {
return number;
} else {
/* 将格式化规则分类 */
var regFl = /\(.\)$/;
var rule_d = regFl.exec(rule)[0].charAt(1);
if (isNaN(rule_d)) {
/* 日期 */
return number.substr(0, 4) + rule_d + number.substr(4, 2) + rule_d + number.substr(6, 2);
} else if (rule_d == 0) {
return parseInt(number).toString().replace(/(\d{1,3})(?=(\d{3})+$)/g, '$1,');
} else {
/* 格式化数字,千分位加分隔符,保留小数 */
var right = '';
var reg = /\./;
if (!reg.test(number)) {
var left = parseInt(number).toString().replace(/(\d{1,3})(?=(\d{3})+$)/g, '$1,');
for (var i = 0; i < rule_d; i++) {
right += '0';
}
return left + '.' + right;
} else {
return Number(number).toFixed(rule_d).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}
}
}
} else {
return number;
}
},
/* 获取title */
getTitle: function(param) {
var regT = /\,formatN/;
if (regT.test(param)) {
return param.split(',')[0];
} else {
return param;
}
},
/* 获取格式化规则 */
getRule: function(param2) {
var regT2 = /\,formatN/;
if (regT2.test(param2)) {
return param2.split(',')[1];
} else {
return 1;
}
},
/*
* 格式化数据结束
*/
涉及到正则、字符串、数组的相应知识。格式化的方式是由后端决定的。
{
"state": true,
"data": {
"key": "idb:act:bonusgroup",
"data": [{
"k0": 20180625,
"k1": "Centroids: 0, 1, 2, 3, 4<br>",
"k2": "Centroids: 1, 3, 6, 9, 26<br>",
"k3": "Centroids: 1, 3, 6, 9, 26<br>"
}],
"wordbook": {
"k0": "日期,formatN(-)",
"k1": "金额,formatN(2)",
"k2": "数字,formatN(0)",
"k3": "其他"
}
}
}