我有一个用户控件,上面有一个 RadioButtonList。
<asp:RadioButtonList ID="rblMyOptions" runat="server" RepeatLayout="Flow"
RepeatDirection="Horizontal" >
<asp:ListItem Text="Yes" Value="Y" onClick="getCheckedRadio(true);" />
<asp:ListItem Text="No" Value="N" onClick="getCheckedRadio(false);" />
</asp:RadioButtonList>
正如您所看到的,我最初设置了一个 onClick 事件来激活 JavaScript 函数,该代码位于页面上,它运行良好,但自从转移到用户控件后,它已停止调用它。
代码包含以下消息:“验证 (ASP.Net):属性“onClick”不是元素“ListItem”的有效属性。
无论如何,我可以有一个 onClick 样式事件来调用我的函数吗?我见过一些例子,它们不断地迭代项目,然后确定选择哪个,但我有很多这样的单选按钮,所以如果可能的话,我宁愿不使用它。
最佳答案
考虑将此 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 绑定(bind)到每个单选按钮的单击事件,因为“单选按钮列表”实际上并不存在于 HTML 中。
您可以查看此问题/答案以获取更多信息: ASP.NET radiobuttonlist onclientclick
通过使用 JQuery 定位任何input[type='radio']
,我们将 javascript 绑定(bind)到任何单选按钮输入(或者我们也可以采取更多限制)。
关于javascript - RadioButtonList ListItem OnClick 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24125455/