【发布时间】:2018-10-22 11:25:46
【问题描述】:
我想在单击标题复选框时选中表中的所有复选框。我不知道该怎么做。这是我到目前为止所做的。
<table class="table" id="myTable">
<thead>
<tr>
<th>
<input type="checkbox" id="selectAll" />
</th>
<th>
@Html.DisplayNameFor(model => model.SNumber)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.Quantity)
</th>
<th></th>
</tr>
</thead>
@foreach (var item in Model)
{
@Html.HiddenFor(model => item.PartNumber)
<tr>
<td>
@Html.CheckBoxFor(modelItem => item.Transfer)
</td>
<td>
@Html.DisplayFor(modelItem => item.SNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Quantity)
</td>
<td>
@Html.ActionLink("Edit", "EditDetails", new { id = item.PartNumber }) |
@Html.ActionLink("Delete", "Delete", new { id = item.PartNumber }, new { onclick = "return confirm('Are sure wants to delete?');" })
</td>
</tr>
}
<script>
$('#selectAll').click(function (e) {
$(this).closest('table').find('td input:checkbox').prop('checked', this.checked);
});
</script>
这是控制台返回的内容:
未捕获的引用错误:$ 未定义
我该如何克服它?我是 MVC 的新手。我们将不胜感激。
【问题讨论】:
-
什么不起作用?您在浏览器控制台中遇到什么错误?
-
请将您的 javascript 更改为 $('#myTable').find('td input:checkbox').prop('checked', this.prop('checked'));
-
“我不知道该怎么做”。我想你会的。演示:jsfiddle.net/4ofw0rn8 您的代码已经工作,假设 Razor CheckBoxFor 输出您期望的内容。您的功能中唯一可能缺少的是,如果用户再次取消选中单个复选框,从逻辑上讲,它也应该同时取消选中“全选”框。但这是您需要编写的单独的代码行。到目前为止,您所写的内容实际上没有任何问题。如果它对您不起作用,您需要向我们提供更多信息,例如任何控制台错误等。
-
从调试脚本开始——例如
cnsole.log($(this).closest('table').find('td input:checkbox').length);返回什么? -
好的,所以您确实遇到了控制台错误。如果您还没有解决(您可以将错误粘贴到谷歌并获得 1000 条结果),这意味着您的页面中没有包含 jQuery。
标签: javascript jquery asp.net-mvc razor