[英]Javascript on ASP.NET Master page not running on content page in subdirectory
[英]javascript error in ASP.NET content page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
function Test1(w) {
document.getElementById('<%=TextBox1.ClientID%>').style.width = w;
return false;
}
Test1(10); // This line arises an error. Why ?
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="button" onclick="Test1(10)" />
</asp:Content>
從腳本調用函數Test1(10)時出現錯誤。 但是當它單擊按鈕時,它可以正常工作。 如何從腳本中調用函數(或如何在ASP.NET Content Page
訪問onload()
函數)?
當您在<script>
塊內調用“ Test1()”時,該輸入字段尚未成為DOM的一部分。 因此,對getElementById()
的調用將返回null
並且該函數的第一行將失敗。
如果移動<script>
塊到文本框后 ,它應該工作。
編輯 -您也可能想在寬度上顯式附加“ px”。
嘗試這個
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
function Test1(w) {
document.getElementById('<%=TextBox1.ClientID%>').style.width = w;
return false;
}
window.onload = function() {
Test1(10); // This line arises an error. Why ?
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button1" type="button" value="button" onclick="Test1(10)" />
</asp:Content>
這是因為在腳本中執行Test1時,文本框不存在。 您要么必須將調用放置在document.ready函數中,要么將其移至文本框之后的頁面下方。
首先,每次您要執行JavaScript代碼時,甚至直接從標記ether中執行事件,都必須等待加載dom級別。 因此可以做類似的事情:
<script type="text/javascript">
window.onload =function()
{ /* code */ }
</script>
或在body標簽的“ onload”事件中執行代碼:
<body onload="Test1(10);">
</body>
或者,如果您使用JQuery,則可以使用上面的代碼:
<script type="text/javascript">
$(document).ready(function(){
/* Code to execute */
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.