MVC Razor页面:如何用jQuery获取选中按钮的Value、标签及循环索引?
问题解决思路及代码修正
核心问题分析
- 重复ID导致元素获取失败:循环生成的按钮共用同一个
id="ddlSectionButtons",HTML中ID必须唯一,因此$('#ddlSectionButtons')永远只能获取到第一个按钮。 - 事件绑定冗余且指向错误:用
.each()遍历后重复给所有.ddlSectionButtons绑定点击事件,不仅会触发多次,还没正确指向当前点击的按钮。 - 未传递循环索引信息:循环时的索引值没有存储到前端元素上,无法直接获取。
第一步:修正Razor视图的按钮生成代码
调整循环逻辑,给每个按钮添加唯一标识、存储索引和文本的属性,同时修正语法错误:
@for (int i = 0; i < Model.Section.Count; i++) { <input type="submit" name="@Html.NameFor(model => model.Section)" value="@Model.Section[i].Value" id="ddlSectionButtons_@i" class="ddlSectionButtons" data-index="@i" data-text="@Model.Section[i].Text" /> }
说明:
- 用
data-index存储循环的索引值,data-text存储按钮显示文本(如果Value和Text一致可省略,留着更灵活)- ID改为
ddlSectionButtons_@i保证每个按钮ID唯一- 移除了冲突的重复
onclick属性,改用jQuery统一绑定事件
第二步:修正jQuery代码
直接通过class绑定点击事件,用this精准指向当前点击的按钮,获取所需信息:
$(function() { $(".ddlSectionButtons").on("click", function(e) { // 可选:如果需要先获取信息再提交,暂时阻止默认表单提交行为 // e.preventDefault(); var $currentBtn = $(this); // 获取选中按钮的Value值 var sectionValue = $currentBtn.val(); // 获取按钮显示文本 var sectionText = $currentBtn.data('text'); // 获取循环时的索引值 var sectionIndex = $currentBtn.data('index'); // 验证并输出信息 if (sectionValue) { alert(`索引: ${sectionIndex},Section文本: ${sectionText},Section值: ${sectionValue}`); } // 如果需要提交表单,手动触发(不需要可删除) // $currentBtn.closest('form').submit(); }); });
说明:
$(this)直接指向当前点击的按钮,避免误取其他元素- 通过
data()方法读取存储在按钮上的索引和文本信息- 可根据需求控制是否立即提交表单,灵活调整逻辑
额外优化建议
- 用
foreach循环搭配索引更简洁:
@foreach (var item in Model.Section.Select((section, index) => new { section, index })) { <input type="submit" name="@Html.NameFor(model => model.Section)" value="@item.section.Value" id="ddlSectionButtons_@item.index" class="ddlSectionButtons" data-index="@item.index" data-text="@item.section.Text" /> }
- 如果不需要表单提交,把按钮类型改为
button更合理:type="button"
内容的提问来源于stack exchange,提问作者Chris Singleton
相关产品推荐
相关产品推荐

