简体   繁体   English

ASP.NET内容页面中的javascript错误

[英]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>

I get error when the function Test1(10) is called from the script. 从脚本调用函数Test1(10)时出现错误。 But when it called on the click of button, it works fine. 但是当它单击按钮时,它可以正常工作。 How can I call the function from the script(OR how I can access the onload() function in an ASP.NET Content Page )? 如何从脚本中调用函数(或如何在ASP.NET Content Page访问onload()函数)?

When your call to "Test1()" inside the <script> block happens, that input field is not yet part of the DOM. 当您在<script>块内调用“ Test1()”时,该输入字段尚未成为DOM的一部分。 Thus the call to getElementById() will return null and the first line of the function will fail. 因此,对getElementById()的调用将返回null并且该函数的第一行将失败。

If you move the <script> block to after the text box, it should work. 如果移动<script>块到文本框 ,它应该工作。

edit — also you may want to explicitly append "px" to your width. 编辑 -您也可能想在宽度上显式附加“ px”。

try this 尝试这个

<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>

It's because the textbox doesn't exist when you execute Test1 in the script. 这是因为在脚本中执行Test1时,文本框不存在。 You either have to place the call in a document.ready function or move it further down the page, after the textbox. 您要么必须将调用放置在document.ready函数中,要么将其移至文本框之后的页面下方。

First of all you every time you want to execute javascript code, even directly from the tag ether from events you have to wait to load the dom level. 首先,每次您要执行JavaScript代码时,甚至直接从标记ether中执行事件,都必须等待加载dom级别。 So can do something like : 因此可以做类似的事情:

  <script type="text/javascript">
      window.onload =function()
      { /* code */ }
  </script>

Or execute your code in the "onload" event of the body tag: like 或在body标签的“ onload”事件中执行代码:

    <body onload="Test1(10);">
    </body>

Or if you use JQuery you can use the above : 或者,如果您使用JQuery,则可以使用上面的代码:

  <script type="text/javascript">
      $(document).ready(function(){
        /* Code to execute */
      });
  </script>

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

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