代码之家  ›  专栏  ›  技术社区  ›  Eric Belair

为什么我的JavaScript变量不能跨函数持久化?

  •  1
  • Eric Belair  · 技术社区  · 16 年前

    我的HTML页面中有以下JavaScript引用页面上的HTML表单:

    <script type="text/javascript">
    <!--
    
    var myForm = document.myForm;
    
    function validateForm() {
        if (myForm.myInput == "")
            alert("Please input some text.");
    
            return false;
        }
    
        myForm.submit();
    }
    
    function showFormInput() {
        myForm.reset();
    
        document.getElementById('myInput').style.display = 'inline';
    }
    
    //-->
    </script>
    
    ...
    
    <form name="myForm" id="myForm" action="..." method="post">
        <input id="myInput" name="myInput" type="text" value="" style="display:none;" />
    </form>
    

    这两个函数在尝试访问变量时都会引发异常 myForm

    更新:

    3 回复  |  直到 16 年前
        1
  •  10
  •   bobobobo    16 年前

    你用什么浏览器?

    一般来说,你不应该使用 document.*

    var myForm = document.getElementById( 'myForm' ) ;
    var myInput = document.getElementById( 'myInput' ) ;
    
    if( myInput.value == '' )
    {
        // its empty!
    }
    

    onload 事件(<车身>标签,像这样

    <script>
    function go()
    {
        alert( "The DOM has been assembled and can be accessed.. nOW!!!" ) ;
        var myForm = document.getElementById( 'myForm' ) ; // ...
    }
    </script>
    <body onload="go() ;">
    </body>
    
        2
  •  7
  •   outis    16 年前

    document.getElementById (或 document.forms. formName ),您需要延迟设置 var myForm 直到处理完表单元素或, better yet

        3
  •  7
  •   Community Mohan Dere    9 年前

    你的问题出在 document.myForm

    var myForm = document.getElementById('myForm');
    

    更新 :其他答案抓住了另外两个问题:

    As bobobobo noted in another answer ,您应该使用 document.getElementById() myForm.myInput 也。此外 outis caught another problem 你应该把你的 <script> 在HTML文档结尾附近,在关闭之前 </body>