【发布时间】:2012-02-21 23:12:52
【问题描述】:
我正在使用 Asp.Net 的 CheckBoxList 控件。为了获得选中的复选框,我在将数据绑定到复选框列表后为 Value 添加了一个自定义属性。
我能够在 jQuery 中获得选中的复选框,但我不知道如何使用复选框列表中的自定义属性找到特定的复选框。
代码如下:
在.cs文件中数据绑定后:
foreach (ListItem li in cblRequestTypes.Items)
li.Attributes.Add("itemValue", li.Value);
获取选中的复选框:
$(":checkbox").each(function() {
if (this.checked) {
selectedChecks += $(this).parent().attr("itemValue") + "~";
}
});
现在我正在传递查询字符串中的值,并且基于此我必须找到在查询字符串中发送了 itemValue 属性的复选框。这部分不起作用,或者我可能在这里遗漏了一些东西。
var id = $.QueryString["id"]
$(id.split("~")).each(function (i, item) {
$("checkbox[itemValue=" + item +"]").attr('check',checked');
});
CheckBoxList 的 HTML 是这样呈现的:
<span itemValue="3"><input id="chkBoxList_0" type="checkbox" name="chkBoxList$0" /><label for="chkBoxList_0">Text 1</label></span>
<span itemValue="5"><input id="chkBoxList_1" type="checkbox" name="chkBoxList$1" /><label for="chkBoxList_1">Text 2</label></span>
<span itemValue="6"><input id="chkBoxList_2" type="checkbox" name="chkBoxList$2" /><label for="chkBoxList_2">Text 3</label></span>
<span itemValue="7"><input id="chkBoxList_3" type="checkbox" name="chkBoxList$3" /><label for="chkBoxList_3">Text 4</label></span>
<span itemValue="8"><input id="chkBoxList_4" type="checkbox" name="chkBoxList$4" /><label for="chkBoxList_4">Text 5</label></span>
<span itemValue="9"><input id="chkBoxList_5" type="checkbox" name="chkBoxList$5" /><label for="chkBoxList_5">Text 6</label></span>
【问题讨论】:
-
我会回答这个问题,条件是你再也不会用
~做奇怪的事情了。我已经清理了一个包含它的 ASP 项目。 -
为什么不使用任何输入元素已有的
value属性?或者将itemValue放在复选框本身上?或者,如果您使用的是 HTML5,请使用data-item-value属性 - 那么您的标记仍然有效 -
@Incognito : ~ 怎么了?它只是一个分隔符。我也可以使用逗号,但我的文本可能包含逗号,所以我选择了 ~。
-
如果我使用 ~ 怎么办?添加/删除复选框时会发生什么?
-
@Incognito:我明白你的意思。我最好在 showmodaldialog 中传递数组而不是查询字符串值。
标签: javascript jquery asp.net checkboxlist