1

我有一个 Web 用户控件,可以在客户端上生成以下 html。

我想使用 JavaScript 引用特定的 RadioButton 控件。

我不确定如何执行此操作,因为 RadioButton ID 是由 asp.net 生成的。

例如我给 RadioButton ID =1_RadioButton

asp.net 生成一个 ID =ctl00_ContentPlaceHolder1_Material_1_RadioButton

这个 javascript 代码如何找到单选按钮控件?

    <script type="text/javascript">
        $(document).ready(function() {
            if (document.getElementById("1_RadioButton").checked) {
                $("#1_other").hide();
            }
        });    
    </script>

以下是 asp.net 为客户端生成的内容。

    <input id="ctl00_ContentPlaceHolder1_Material_1_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="1_RadioButton" onclick="javascript:$('#1_other').show('fast');" />

    <label for="ctl00_ContentPlaceHolder1_Material_1_RadioButton">Yes</label>

    <input id="ctl00_ContentPlaceHolder1_Material_2_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="2_RadioButton" checked="checked" onclick="javascript:$('#1_other').hide('fast');" />

    <label for="ctl00_ContentPlaceHolder1_Material_2_RadioButton">No</label>

    <input id="ctl00_ContentPlaceHolder1_Material_3_RadioButton" type="radio" name="ctl00$ContentPlaceHolder1$Material$Academic" value="3_RadioButton" onclick="javascript:$('#1_other').hide('fast');" />

    <label for="ctl00_ContentPlaceHolder1_Material_3_RadioButton">Uncertain</label>

    <div id='1_other'>
         <input name="ctl00$ContentPlaceHolder1$Material$4_TextBox" type="text" value="bbb chabng" id="ctl00_ContentPlaceHolder1_Material_4_TextBox" />
   </div>
4

4 回答 4

6

如果该代码在 .aspx 文件中,请使用 <%= MyRadioButton.ClientID %> 代替它,ASP.NET 呈现引擎将为您正确呈现 ID。

更新:例如:

<script type="text/javascript">
    $(document).ready(function() {
        if ($get("<%= MyRadioButton.ClientID %>").checked) {
            $("#1_other").hide();
        }
    });    
</script>
于 2009-05-07T17:58:54.837 回答
1
var radioButton = document.getElementById("<%= 1_RadioButton.ClientID %>");

然后从那里去。注意 - 我对引号不肯定。

于 2009-05-07T17:59:24.507 回答
-1

我写了一篇关于如何做到这一点的博客文章:

假设您的页面上有一个标签控件:

生成的 html 输出和该控件的 ID 可能如下所示:

<span id="ctl00_ContentPlaceHolder1_Label1"></span>

不幸的是,生成的 ct100_ContentPlaceHolder1_Label1 的 ID 在构建之间并不总是相同的。所以尝试像这样选择它:

$("#ct100_ContentPlaceHolder1_Label1").hide();

最终会中断,它不会隐藏标签控件。

诀窍是在 jQuery 选择器中使用 ASP.NET。Label1.ClientID 每次都会返回生成的 ID。我们将 ASP.NET 和 jQuery 组合成一行,如下所示:

$("#<%= Label1.ClientID %>").hide();

这将每次都获得Label控件的生成ID。

于 2009-05-07T18:08:24.203 回答
-1

非常简单,只需将clientidmodeWeb 控件的设置为静态 ( clientidmode="static"),您就可以确定这asp.net将保持您ID在设计器 UI 中的外观。

于 2012-04-14T08:44:17.417 回答