考虑把这个 JQuery 或一些变体放在你的主窗体上。
//On document ready
$(function() {
$("input[type='radio']").on('click', function(e) {
getCheckedRadio($(this).attr("name"), $(this).val(), this.checked);
});
});
//External function to handle all radio selections
function getCheckedRadio(group, item, value) {
$(".group-label").text(group);
$(".item-label").text(item);
$(".item-value").text(value);
}
然后在你的部分:
<asp:RadioButtonList ID="rblMyOptions" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
<asp:ListItem Text="Yes" Value="Y" />
<asp:ListItem Text="No" Value="N" />
</asp:RadioButtonList>
这应该处理所有的单选按钮(或者如果你改变了它,至少是你用 JQuery 定位的那些)。
我在这里有一个工作示例(没有 .NET 代码)来演示该原理。
http://jsfiddle.net/xDaevax/UwEN5/
编辑:这基本上是幕后发生的事情。
我不确定你对这件事有多陌生,所以我会在这里详细介绍一下,如果你已经掌握了其中一些事情,我深表歉意。
当您使用 .NET 控件(asp:DropDownList、asp:RadioButtonList、asp:ListItem)时,这些都是在将页面发送到浏览器时生成的服务器端表示。您在 .aspx 页面中看到的代码不一定是标记发送到浏览器的方式。
例如下面的代码:
<asp:Label ID="_CtlMyLabel" runat="server" Text="Label" />
将在浏览器 HTML 中呈现为:
<span id="_CtlMyLabel">Label</span>
如果你将它包装在一个面板中:
<asp:Panel ID="_CtlWrapperPanel" runat="server" ClientIDMode="Inherit">
<asp:Label ID="_CtlMyLabel" runat="server" Text="Label" ClientIDMode="Inherit" />
</asp:Panel>
你会得到:
<div id="_CtlWrapperPanel">
<span id="_CtlMyLabel">Label</span>
</div>
说到一个RadioButtonList,如下asp:RadioButtonList:
<asp:RadioButtonList ID="rblMyOptions" runat="server" RepeatLayout="Flow" RepeatDirection="Horizontal">
<asp:ListItem Text="Yes" Value="Y" />
<asp:ListItem Text="No" Value="N" />
</asp:RadioButtonList>
将生成:
<span id="rblMyOptions">
<input id="rblMyOptions_0" type="radio" name="rblMyOptions" value="Y" />
<label for="rblMyOptions_0">Yes</label>
<input id="rblMyOptions_1" type="radio" name="rblMyOptions" value="N" />
<label for="rblMyOptions_1">No</label>
</span>
当您在 ListItem 上说 OnClick 时,.NET 认为您指的是您创建的名为 rblMyOptions_Click 的服务器端函数(它将执行回发),但由于您希望这发生在客户端上,所以我的策略是建议解决它是使用JQuery绑定到每个单选按钮的点击事件,因为“单选按钮列表”实际上并不存在于HTML中。
您可以查看此问题/答案以获取更多信息:
ASP.NET radiobuttonlist onclientclick
通过使用 JQuery 来定位任何 input[type='radio'],我们将 javascript 绑定到任何单选按钮输入(或者我们也可以更加严格)。