【发布时间】:2014-06-06 09:27:39
【问题描述】:
我有一个 ASP.NET MVC 剃须刀页面,它有一个循环,循环中有一个 CheckboxFor。我为每个复选框分配了一个数字值。我还分配了一个类,以便当这些复选框值中的任何一个发生更改时,我可以在 jquery 中捕获 onchange 事件:
@Html.CheckBoxFor(modelItem => item.PrincipleInvestigator, new { Value = item.ProjectResearcherId, @class = "Principle-investigator-checkbox" })
然后,在 jquery 中,我想要被点击的特定复选框的数值:
$(".Principle-investigator-checkbox").change(function () {
alert($(".Principle-investigator-checkbox").val);
});
这是行不通的。我实际上不知道如何确定单击了列表中的哪个复选框。 this.val 之类的东西?另外,我不确定.val 是否给了我分配给它的数值,但是如果我检查呈现的 HTML,可以看到该值:
<input value="4570" class="Principle-investigator-checkbox" data-val="true" data-val-required="The PrincipleInvestigator field is required." id="item_PrincipleInvestigator" name="item.PrincipleInvestigator" type="checkbox">
【问题讨论】:
-
这是
$(".Principle-investigator-checkbox").val()而不是$(".Principle-investigator-checkbox").val -
另外,处理
click事件而不是change。它更适合checkboxes。 -
此外,在事件处理程序中,您可以通过
$(this)引用元素。您不需要重复选择器,它将引用接收事件的元素,而不是第一个(如果您有多个共享相同的class)。 -
开始理解
jQuery的好方法是阅读以下内容:api.jquery.com
标签: jquery asp.net asp.net-mvc razor checkbox