繁体   English   中英

javascript和asp.net网络用户控件

[英]javascript and asp.net web user controls

我有一个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>

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

更新:例如:

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

然后从那里去。 注意-我对引号不太满意。

非常简单,只需将Web控件的clientidmode设置为static( clientidmode="static" ),就可以确保asp.net将保留您的ID如在设计器UI中所示。

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

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

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM