简体   繁体   English

函数Javascript无法访问全局变量

[英]Global Variables not Accessible to Functions Javascript

I am using javascript to validate the information a user has put into a form. 我正在使用JavaScript来验证用户输入到表单中的信息。 I have two functions in my code which both need to check that the information in two text fields is the same. 我的代码中有两个函数,都需要检查两个文本字段中的信息是否相同。 One function is called when the form is submitted, the other when something is typed into the second field. 提交表单时调用一个函数,在第二个字段中键入内容时调用另一个函数。

However neither function seems to be able to access these variables. 但是,两个函数似乎都无法访问这些变量。 Google Developer tools shows their value to be Null. Google Developer工具显示其值为Null。 The code works fine when I declare the variables within each function but I thought it should be possible to declare them just once 当我在每个函数中声明变量时,代码工作正常,但我认为应该可以只声明一次

var user1 = document.getElementById('user1');
var user2 = document.getElementById('user2');

function validateText() {
    var message2 = document.getElementById('confirmMessage');  
    if(user1.value !== user2.value) {
        message2.innerHTML = "Your usernames must be the same!";   
        return false;
    }
}

function checkUser() {
    //Store the Confimation Message Object ...
    var message = document.getElementById('confirmMessage');
    //Compare the values in the user field 
    //and the confirmation field
    if(user1.value == user2.value) {
        //The usernames match. 
        // tell the user that they have entered the correct password 
        message.innerHTML = "Passwords Match!"
    }
}

you need to define these variables after the document is loaded. 您需要在文档加载后定义这些变量。

var user1, user2;
document.onload = function () {
    user1 = document.getElementById('user1');
    user2 = document.getElementById('user2');
}

If the user1 and user2 elements are created by Javascript or by HTML that is placed after the JS (perhaps you are inserting this JS in the head section) then they still dont exist when you first run your script. 如果user1和user2元素是由Javascript或放置在JS之后的HTML创建的(也许您是在头部插入此JS),则在您第一次运行脚本时它们仍然不存在。 This means that the getElementById variables will not find anything and return null. 这意味着getElementById变量将找不到任何东西并返回null。

You need to make sure that you call getElementByID after the apropriate elements have been created. 您需要确保在创建适当的元素后调用getElementByID。 ONe easy way to do that is put the calls inside the validation functions but another possibility would be to put it in an onLoad handler. 一种简单的方法是将调用放入验证函数中,但另一种可能性是将其放入onLoad处理程序中。

I would prefer sticking them in the validators though - getting elements by ID is not an expensive operation (so you don't need to worry about performance) and the closer you fetch the data to when you use it the less stuff to worry about. 不过,我更希望将其粘贴在验证器中-通过ID获取元素并不是一项昂贵的操作(因此您不必担心性能),并且在使用数据时越接近获取数据,您所担心的事情就越少。

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

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