DIV CSS 佈局教程網

用 JS 在用戶端實現 CheckBoxList 的全選與反選
編輯:關於JavaScript     

對於 CheckBoxList 控制項而言,一方面要在伺服器端完成大量資料的綁定,另一方面往往還需要全選、反選等互動功能。這些工作雖然也能在伺服器端處理,但這類單純的介面操作顯然更適合成在用戶端完成,以減少不必要的伺服器往返。

具體方法:

先在頁面中放入一個 CheckBoxList 控制項並加入幾個項目,藉此分析它產生的 HTML 結構,這樣在撰寫 JS 動態控制時就會清晰許多。測試用的控制項如下:

參考程式碼 如下:

<asp:CheckBoxList ID="CheckBoxList1" runat="server" CellPadding="3" CellSpacing="3"
RepeatColumns="3">
<asp:ListItem>1232</asp:ListItem>
<asp:ListItem>254</asp:ListItem>
<asp:ListItem Value="5643">5643</asp:ListItem>
<asp:ListItem>789</asp:ListItem>
<asp:ListItem>654</asp:ListItem>
<asp:ListItem>564</asp:ListItem>
<asp:ListItem>8564</asp:ListItem>
<asp:ListItem>8564</asp:ListItem>
<asp:ListItem>5452</asp:ListItem>
<asp:ListItem>5641</asp:ListItem>
</asp:CheckBoxList>

在瀏覽器中檢視並分析它生成的 HTML:

參考程式碼 如下:

<table id="CheckBoxList1" cellspacing="3" cellpadding="3" border="0">
<tr>
<td><input id="CheckBoxList1_0" type="checkbox" name="CheckBoxList1$0"/><label for="CheckBoxList1_0">1232</label>
</td>
<td><input id="CheckBoxList1_4" type="checkbox" name="CheckBoxList1$4"/><label for="CheckBoxList1_4">654</label>
</td>
.......
</table>

從這段結構可以觀察到,CheckBoxList 會產生許多 type 為 checkbox 的 input,且其 ID 命名規則為「CheckBoxList1_i」(i 為數字)。因此我們只要知道一共有幾項,就能輕鬆用 JS 控制它。由於這些 input 都被包在一個 id 為 CheckBoxList1 的 table 中,因此可以透過下面這段程式取得總項目數:

參考程式碼 如下:

document.getElementById("CheckBoxList1").getElementsByTagName("input").length

接著加入三個按鈕,分別負責全選、反選與清除:

參考程式碼 如下:

<input type="button" onclick="checkAll()" value="checkAll"/>
<input type="button" onclick="ReverseAll()" value="ReverseAll" id="Button1"/>
<input type="button" onclick="deleteAll()" value="deleteAll"/>

再補上三個對應的函式:

參考程式碼 如下:

function checkAll(){
for(var i=0;i<document.getElementById("CheckBoxList1").getElementsByTagName("input").length;i++)
{
document.getElementById("CheckBoxList1_"+i).checked=true;
}
}
function deleteAll(){
for(var i=0;i<document.getElementById("CheckBoxList1").getElementsByTagName("input").length;i++)
{
document.getElementById("CheckBoxList1_"+i).checked=false;
}
}
function ReverseAll(){
for(var i=0;i<document.getElementById("CheckBoxList1").getElementsByTagName("input").length;i++)
{
var objCheck=document.getElementById("CheckBoxList1_"+i);
if(objCheck.checked)
objCheck.checked=false;
else
objCheck.checked=true;
}
}

三個函式的邏輯都很清楚:checkAll 逐一將 checked 設為 true 達成全選、deleteAll 逐一設為 false 達成清除、ReverseAll 則是逐項判斷並反轉目前的勾選狀態。如此一來,資料綁定可以放在後台,而全選、反選等輔助功能便能完全在用戶端自由發揮了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved