将变量从html中的JS代码传递给分离的JS代码,并不起作用

时间:2014-02-09 08:30:46

标签: javascript html

first.html

<!DOCTYPE html>
<html>

</head>

<body>
            <form>
                <script type="text/javascript">

                    // grab the id number
                    var theIdNumber = localStorage.getItem("idNumber");

                    // set the ID in the HTML page
                    document.getElementById("userId").value = theIdNumber;
                </script>

                <button type="button" onClick="validateUsernamePassword()">SEND</button>
            </form> 
</body>
</html>

other.js

function validateUsernamePassword()
{    
            var idNum = $("#userId").val(); 
            alert('Well the id is :' + idNum);

            // more code 
}

警报不会打印传递的ID ...为什么?

2 个答案:

答案 0 :(得分:2)

像这样修改你的html:

<html>
<head>
<title></title>
</head>
        <body>
                    <form>


                        <button type="button" onClick="validateUsernamePassword()">SEND</button>
                        <input type="hidden" id="userId"></input>
                    </form> 
                        <script type="text/javascript">

                            // grab the id number
                            var theIdNumber = localStorage.getItem("idNumber");

                            // set the ID in the HTML page
                            document.getElementById("userId").value = theIdNumber;
                        </script>
        </body>

    </html>

或者你可以做到这一点:

function validateUsernamePassword()
{    
            var idNum = localStorage.getItem("idNumber"); 
            alert('Well the id is :' + idNum);

            // more code 
}

第二个是好的,因为你已经在localstorage中有了这个项目,所以不需要将它的值赋给另一个元素

答案 1 :(得分:0)

这个技巧可以帮到你:

<html>
<head>

</head>
<body>
<dl>
<script>
    window.var1 = "hello, world";

</script>
<input type="button" value="click" onclick="clicked()">

<script>
    function clicked(){
        alert(window.var1);
    };

</script>
</body>