Ps:本例使用jquery-1.11.3.js
本例的功能为合并<th>,检测字符为下划线
前>>
后>>
<table>
<tr><th>cdhe</th><th>cd_he</th><th>cd_s12_1</th><th>cd_s12_2</th><th>ad_he</th><th>cdhe</th><th>cd_he</th><th>cd_s12_1</th><th>cd_s12_2</th><th>ad_he</th></tr>
<tr><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td><td>dcde</td></tr>
</table>
$(function () {
$.fn.muliTh = function () {
var arrs = [], a1 = [], maxLength = 0;
var that = $(this);
that.find('th').each(function () {
a1 = $(this).html().replace(/^\s|\s$/g, "").replace(/\s+/g, "").split('_');
maxLength < a1.length ? maxLength = a1.length : 1;
arrs.push(a1);
})
that.find('th').hide();
var createTh = '';
for (i = 0; i < maxLength; i++) {
createTh += "<tr class='jg_func jg_muliTh'>";
for (a = 0; b = that.find('th').length, a < b; a++) {
if (arrs[a][i]) {
createTh += "<th colspan='1' par='" + (function (list, para) {
return para - 1 < 0 ? 'par' : list[para - 1];
})(arrs[a], i) + "' rowspan='" + (function (x, y, z) {
var rs = 1;
!y[z + 1] ? rs = x + 1 - y.length : rs = 1;
return rs;
})(maxLength, arrs[a], i) + "'>" + arrs[a][i] + "</th>"; //(maxLength + 1 - arrs[a].length)
}
}
createTh += "</tr>";
}
that.prepend(createTh);
$('.jg_muliTh').each(function () {
$(this).find('th').each(function () {
var a2 = $(this);
if (a2.html() === a2.prev().html() && a2.attr('par') === a2.prev().attr('par')) {
a2.prev().attr('colspan', 1 + +a2.prev().attr('colspan'));
a2.remove();
}
})
})
console.log(arrs);
}
})
window.onload = function () {
$('table').muliTh();
}