读书人

JQ跟JS动态拆分表格的方法

发布时间: 2013-07-09 09:50:48 作者: rapoo

JQ和JS动态拆分表格的方法

                                                                            
[解决办法]
拆分单元格的方法;
<html>
<head>
<script>
function split() {
var cell1 = document.createElement("td");
cell1.setAttribute("style", "background-color: grey;");
cell1.innerHTML = "Product1";

var cell2 = document.createElement("td");
cell2.innerHTML = "VS";

var cell3 = document.createElement("td");
cell3.setAttribute("style", "background-color: grey;");
cell3.innerHTML = "Product2";

myTable.rows[0].removeChild(myTable.rows[0].cells[0]);

var typeCell = myTable.rows[0].cells[0];



typeCell.parentNode.insertBefore(cell1, typeCell);
typeCell.parentNode.insertBefore(cell2, typeCell);
typeCell.parentNode.insertBefore(cell3, typeCell);
};
</script>
</head>
<body>
<table id="myTable" border=0>
<tr>
<td colspan="3" style="background-color: grey;">Product1VSProduct2</td>
<td>Type</td>
</tr>
<tr>
<td colspan="3" style="background-color: grey;">Product3</td>
<td>Type</td>
</tr>
</table>
<input type="button" onclick="split()" value="split">
</body>
</html>


想法就是原先定义colspan(因不是每行的此列都需要拆分),然后移除掉单元格,添加新的单元格;
如何判断单元格是不是要划分就不说咯^_^
[解决办法]
给td加一个colspan即可,
<table border=2 width="50%">
<tr>
<td colspan=2> 狮子 </td> </tr>
<tr><td>狮子</td>
<td> 斑马 </td>
</tr>
</table>

或者把 产品1 VS 产品2 3个内容分别用span装起来,然后把span的样式改一下,这样就不用修改td的样式
[解决办法]
给你个最简单的思路。
        function spilt() {
//遍历行
$("table tr").each(function () {
//获取第4列的值
var yy = $(this).children("td").eq(3).html();
var arr = new Array();
//按照VS拆分
arr = yy.split('VS');
//满足条件。如产品1VS产品2,则改变单元格内容
if (arr.length == 2) {
var newTable = "<table width='100%' border='1' style='text-align: center;'><tr><td>" + arr[0].toString() + "</td><td>VS</td><td>" + arr[0].toString() + "</td></tr></table>";


$(this).children("td").eq(3).html(newTable);
}
});
}


[解决办法]
遍历所有的 td内容,如果发现了td内容有需要要拆分的话,就马上这样写
$(this).innerHTML = "<table><tr><td>产品1</td><td>VS</td><td>产品2</td><tr><tablle>";
很简单吧?

读书人网 >JavaScript

热点推荐