Я хотел бы применить некоторую логику к странице, содержащей элемент управления CheckBoxList, когда пользователь проверяет или снимает флажки с отдельных элементов флажков. Скажем, например, чтобы динамически показать или скрыть связанный элемент управления.
Я придумал способ использования механизма обратного вызова ASP.Net 2.0 (AJAX) с комбинацией клиентской Javascript и серверной логики в коде позади. Тем не менее, это решение не является пуленепробиваемым (то есть, скорее всего, страдает от временных проблем). Он не переносим, потому что код должен знать последовательные идентификаторы отдельных элементов и т. Д.
Код, который я создал, разделен на две функции: одна обрабатывает событие 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>
Нет ли более элегантного решения этой проблемы?