![](/img/trans.png)
[英]Ensuring unique Javascript identifiers in ASP.NET Web User Controls
[英]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.