自定義的單元格合併

iteye_20954發表於2011-12-30
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#TableTemp").html($("#Table1").html()); }); function test() { $("#Table1").html($("#TableTemp").html()); var tempval = ""; var $checkedBoxes = $(":checkbox[name='chk']:checked"); if ($checkedBoxes.length <= 1) { alert("至少應該選擇兩列以上才能合併!"); return; } var mergeCols = ""; $checkedBoxes.each(function () { if (tempval != "") { if (Math.abs(parseInt(tempval) - parseInt($(this).val())) != 1) { alert("選中的必須是相鄰的列!"); tempval = "-1"; return false; } } tempval = $(this).val(); mergeCols += $(this).val() + ","; }); if (tempval == "-1") { return; } mergeCols = mergeCols.substring(0, mergeCols.length - 1); var arr = mergeCols.split(","); var startTd = parseInt(arr[0]); var endTd = parseInt(arr[1]); $("#Table1>tbody>tr").each(function () { var tempHtml = ""; $(this).find("td").each(function (index) { if (arr.in_array(index + "")) { tempHtml += $(this).html(); } }); $(this).find("td:eq(" + startTd + ")").attr("colspan", arr.length).html(tempHtml); $(this).find("td").each(function (index) { if (index!=startTd && arr.in_array(index + "")) { $(this).remove(); } }); }); } Array.prototype.in_array = function (e) { for (i = 0; i < this.length && this[i] != e; i++); return !(i == this.length); } </script> </head> <body> <input type="checkbox" name="chk" value="0" />1 <input type="checkbox" name="chk" value="1" />2 <input type="checkbox" name="chk" value="2" />3 <input type="checkbox" name="chk" value="3" />4 <input type="checkbox" name="chk" value="4" />5<br /> <input type="button" value="合併" onclick="test()" /> <table id="TableTemp" style="display:none;"></table> <table border="1 " style="width: 80%" id="Table1"> <thead> <tr style="background-color:#E3EEF2;" ><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> </thead> <tbody> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> </tbody> </table> </body> </html>

相關文章