我想在用戶選中或取消選中單個複選框項目時,將某些邏輯應用於包含CheckBoxList控件的頁面。比方說,動態顯示或隱藏相關的控件。反應點擊CheckboxList中的ListItems
我想出了一種使用ASP.Net 2.0回調機制(AJAX),在代碼隱藏中結合了客戶端Javascript和服務器端邏輯的方法。然而,這個解決方案並不是非常防彈(即很可能會遇到時間問題)。它不是便攜式的,因爲代碼需要知道單個項目的順序ID等。
我想出的代碼分爲兩個函數,一個處理onclick
事件,另一個處理返回的回調字符串:
<script type="text/javascript">
function OnCheckBoxClicked()
{
// gathers the semi-colon separated list of labels,
// associated with the currently checked items
var texts = '';
// iterate over each individual checkbox item
// items in a checkboxlist are sequential, so
// stop iteration at the first missing sequence number
for (var index = 0; index < 99; index++)
{
var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index);
if (checkbox == null)
break;
if (checkbox.checked)
{
// find label associated with the current checkbox item
var labels = document.getElementsByTagName('label');
for (var index_ = 0; index_ < labels.length; index_ ++)
{
if (labels[index_].htmlFor == checkbox.id)
{
texts = texts + labels[index_].innerHTML + ';';
break;
}
}
}
}
// perform callback request
// result will be processed by the UpdateCheckBoxes function
WebForm_DoCallback('__Page', '_checkbox' + texts, UpdateCheckBoxes, 'checkbox', null, true /* synchronous */);
}
</script>
在此示例中,我的複選框與博文的類別相匹配。
我需要處理生成的回調字符串,其中包含複選框的分號分隔列表以檢查/取消選中,以確保相關的父/子類別正確同步。該字符串由服務器上執行的邏輯產生。
在其他情況下,生成的回調字符串可能是別的。
<script type="text/javascript">
function UpdateCheckBoxes(returnmessage, context)
{
if (returnmessage == null || returnmessage == '')
return ;
// iterate over each individual checkbox item
// items in a checkboxlist are sequential, so
// stop iteration at the first missing sequence number
for (var index = 0; index < 99; index++)
{
var checkbox = document.getElementById('ctl00_cphAdmin_cblCategories_' + index);
if (checkbox == null)
break;
// find label associated with the current checkbox item
var label = '';
var labels = document.getElementsByTagName('label');
for (var index_ = 0; index_ < labels.length; index_ ++)
{
if (labels[index_].htmlFor == checkbox.id)
{
label = ';' + labels[index_].innerHTML + ';';
break;
}
}
// perform custom processing based on the contents
// of the returned callback string
// for instance, here we check whether the returnmessage
// contains the string ';' + label + ';'
if (returnmessage.indexOf(label, 1) > 0)
{
// do something
}
}
}
</script>
這個問題沒有更好的解決方案嗎?