我试图隐藏/显示一个div基于我的否/是ASP。. NET RadioButtonList所选值。当我在"No"项上没有引导活动类时,我的代码可以工作。当它在"否"项上时,由于某种原因,当用户选择"是"值时,结果是"否"....下面是我的代码:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatLayout="flow" RepeatDirection="Horizontal" CssClass="btn-group" data-toggle="buttons">
<asp:ListItem Text="No" Value="No" Selected="true" class="btn btn-default active"></asp:ListItem>
<asp:ListItem Text="Yes" Value="Yes" class="btn btn-default"></asp:ListItem>
</asp:RadioButtonList>
$('#<%=RadioButtonList1.ClientID%>').click(function () {
debugger;
var value = $("#<%= RadioButtonList1.ClientID %> input:checked").val();
if (value == "Yes") {
$('#<%=Panel1.ClientID%>').hide();
}
if (value == "No") {
$('#<%=Panel1.ClientID%>').show();
}
});
一旦代码生成并发送到客户端:
<span id="GlobalContent_MainContent_RadioButtonList1" class="btn-group" data-toggle="buttons">
<span class="btn btn-default active">
<input id="GlobalContent_MainContent_RadioButtonList1_0" type="radio" name="ctl00$ctl00$GlobalContent$MainContent$RadioButtonList1" value="No" checked="checked">
<label for="GlobalContent_MainContent_RadioButtonList1_0">No</label>
</span>
<span class="btn btn-default">
<input id="GlobalContent_MainContent_RadioButtonList1_1" type="radio" name="ctl00$ctl00$GlobalContent$MainContent$RadioButtonList1" value="Yes" onclick="javascript:setTimeout('__doPostBack('ctl00$ctl00$GlobalContent$MainContent$RadioButtonList1$1','')', 0)"><label for="GlobalContent_MainContent_RadioButtonList1_1">Yes</label>
</span>
</span>
您的点击处理程序在容器上,这可能是您的问题的根源。
- 将事件监听器更新为
change
事件而不是click
事件。 - 因为你正在听一个
change
,你想要更新选择器到实际的输入,改变将被触发。
更新JS/ASP:
$('#<%=RadioButtonList1.ClientID%> input').change(function () {
var $input = $(this),
$target = $('#<%=Panel1.ClientID%>'),
value = $input.val();
if (value === "Yes") {
$target.hide();
} else {
$target.show();
}
});
下面是基于您生成的代码的运行示例:
演示:JSFiddle
在几乎所有情况下,我建议不要将服务器端生成的代码与JavaScript混合。你想把这两者分开有很多原因,但这超出了你的问题范围。