我想在用户选中或取消选中单个复选框项目时,将某些逻辑应用于包含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>
这个问题没有更好的解决方案吗?