今天有做了幾個asp.net結合Javascript的教程文章。現回顧頭來看看那些Javascript腳本,有寫得不太理想,過於復雜。現抽取出來,重構它們。
之前一:
復制代碼 代碼如下:
function SelectedAll(cb) {
cb.checked = cb.checked ? false : true;
var gv = document.getElementById('<%=GridViewCouplets.ClientID %>');
var rc = gv.rows.length;
for (var i = 1; i < rc; i++) {
var input = gv.rows[i].cells[0].getElementsByTagName("input");
if (input[0].type == "checkbox" && input[0].checked) {
input[0].checked = false;
gv.rows[i].style.backgroundColor = "";
}
else {
input[0].checked = true;
gv.rows[i].style.backgroundColor = "#66ff33;";
}
}
}
function SelectedSingle(cb) {
var row = cb.parentNode.parentNode;
if (cb.checked) {
row.style.backgroundColor = "#66ff33;";
}
else {
row.style.backgroundColor = "";
}
}
經過重構之後的Javascript腳本:
復制代碼 代碼如下:
function SelectedAll(cb) {
var gv = document.getElementById('<%=GridViewCouplets.ClientID %>');
var rc = gv.rows.length;
for (var i = 1; i < rc; i++) {
var input = gv.rows[i].cells[0].getElementsByTagName("input");
if (input[0].type == "checkbox")
{
input[0].checked = cb.checked;
gv.rows[i].style.backgroundColor = input[0].checked ? "#66ff33;" :"";
}
}
}
function SelectedSingle(cb) {
var row = cb.parentNode.parentNode;
row.style.backgroundColor = cb.checked? "#66ff33;":"";
}
之前二:
復制代碼 代碼如下:
function Check_Uncheck_All(cb) {
var cbl = document.getElementById("<%=CheckBoxListMusicType.ClientID%>");
var input = cbl.getElementsByTagName("input");
if (cb.checked) {
for (var i = 0; i < input.length; i++) {
input[i].checked = true;
}
}
else {
for (var i = 0; i < input.length; i++) {
input[i].checked = false;
}
}
}
重構之後的Javascript腳本:
復制代碼 代碼如下:
function Check_Uncheck_All(cb) {
var cbl = document.getElementById("<%=CheckBoxListMusicType.ClientID%>");
var input = cbl.getElementsByTagName("input");
for (var i = 0; i < input.length; i++) {
input[i].checked = cb.checked;
}
}