最近在学习javascript,所以写下例子,练习一下,记录今天,方便以后查看!
JavaScript用的是静态私有变量,每个实例都没有自己的私有变量。
Css代码如下:
table {max-width: 100%;background-color: transparent;border-collapse: collapse;border-spacing: 0;}
.table {width: 100%;margin-bottom: 20px;}
.table th,.table td {padding: 8px;line-height: 20px;text-align: left;vertical-align: top;border-top: 1px solid #dddddd;}
.table th {font-weight: bold;}
.table thead th {vertical-align: bottom;}
.table tbody + tbody {border-top: 2px solid #dddddd;}
.table-hover tbody tr:hover td,.table-hover tbody tr:hover th {background-color: #f5f5f5;}
.table tbody tr.success td {background-color: #dff0d8;}
.table tbody tr.error td {background-color: #f2dede;}
.table tbody tr.warning td {background-color: #fcf8e3;}
.table tbody tr.info td {background-color: #d9edf7;}
.table-hover tbody tr.success:hover td {background-color: #d0e9c6;}
.table-hover tbody tr.error:hover td {background-color: #ebcccc;}
.table-hover tbody tr.warning:hover td {background-color: #faf2cc;}
.table-hover tbody tr.info:hover td {background-color: #c4e3f3;}
JavaScript代码如下:
function selectForm(lowerValue, upperValue) {
return Math.floor(Math.random() * (upperValue - lowerValue + 1) + lowerValue);
}
(function() {
var row = 10;
var col = 5;
var classNames = ["success", "error", "warning", "info"];
Table = function() {
if (arguments.length === 1) {
row = arguments[0];
} else if (arguments.length === 2) {
row = arguments[0];
col = arguments[1];
} else if (arguments.length === 3) {
row = arguments[0];
col = arguments[1];
classNames = arguments[2];
}
};
Table.prototype.getRows = function() {
return row;
};
Table.prototype.setRows = function(value) {
row = value;
}
Table.prototype.getCols = function() {
return col;
};
Table.prototype.setCols = function(value) {
col = value;
}
Table.prototype.getclassNames = function() {
return color;
};
Table.prototype.setclassNames = function(value) {
color = value;
}
Table.prototype.createTable = function() {
var data = new Array();
data.push("<table class=\"table table-hover\"><tbody id=\"myTab\">");
for (var i = 0; i < row; i++) {
data.push("<tr>");
for (var j = 0; j < col; j++) {
data.push("<td>(" + i + "," + j + ")</td>");
}
data.push("</tr>");
}
data.push("</table></tbody>");
document.body.innerHTML = data.join("");
};
Table.prototype.setTableRowColor = function() {
var trs = document.getElementById("myTab").getElementsByTagName("tr");
for (var i = 0; i < trs.length; i++) {
trs[i].className = classNames[selectForm(0, classNames.length - 1)];
}
}
})();
var table = new Table();
table.createTable();
table.setTableRowColor();
Html代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>动态创建Table每行随机换色</title>
</head>
<body>
</body>
</html>
运行效果图,如下所示: