用Jquery实现的一个Table的帮助js
主要实现的table的辅助功能有:获得当前td的上,下,左,右的td,获得上下tr,获得当前td所处的行列等。
注意:
表格中最好不要再套表格,否则可能导致方法失效。
每个table必须有一个id以便有些方法使用。
//*********************************************************** //* author:scott qian //* date:2011/07/23 //* description:a table helper js based on JQuery //*********************************************************** /// <reference path="jquery-1.4.1.min.js" /> //Get the current row index(start from 0) function GetCurrentRowIndex(currentTd) { return $(currentTd).parent().prevAll("tr").length; } //Get the current column index(start from 0) function GetCurrentColumnIndex(currentTd) { var num = 0; while (true) { currentTd = $(currentTd).prev("td"); if (currentTd.html() == null) { break; } num++; } return num; } //Get sum row count of the table function GetTableRowCount(tableId) { return $("#" + tableId + " tr").length; } //Get sum column count of current row function GetCurrentRowColumnCount(currentTd) { var tempTd = currentTd; var num = 0; //previous count of currentTd var prevCount = GetCurrentColumnIndex(currentTd); num += prevCount; //next count of currentId while (true) { tempTd = $(tempTd).next("td"); if (tempTd.html() == null) { break; } num++; } //include currentTd itself return num + 1; } //Get the previous td element of current td element function GetPrevTd(currentTd) { return $(currentTd).prev("td"); } function GetPrevTr(currentTd) { return $(currentTd).parent().prev("tr"); } //Get the last td element of current td element function GetNextTd(currentTd) { return $(currentTd).next("td"); } function GetNextTr(currentTd) { return $(currentTd).parent().next("tr"); } //Get the td element above current td element function GetAboveTd(currentTd) { var currentColumn = GetCurrentColumnIndex(currentTd); return GetPrevTr(currentTd).children("td:eq(" + currentColumn + ")"); } //Get the td element below current td element function GetBelowTd(currentTd) { var currentColumn = GetCurrentColumnIndex(currentTd); return GetNextTr(currentTd).children("td:eq(" + currentColumn + ")"); } //Get all odd tr element function GetOddTr(tableId) { return $("#" + tableId + " tr:odd"); } //Get all even tr element function GetEvenTr(tableId) { return $("#" + tableId + " tr:even"); } //Give odd tr elements background color function BackgroundColorOddTr(tableId, color) { GetOddTr(tableId).each(function () { $(this).css("background-color", color); }); } //Give even tr elements background color function BackgroundColorEvenTr(tableId, color) { GetEvenTr(tableId).each(function () { $(this).css("background-color", color); }); }