我正在设置一个变量...否则声明。但是,当我尝试在另一个函数中调用变量时,我收到未定义变量的错误。如何设置全局变量?
function username_check(){
username = $('#username').val();
if(username == "" || username.length < 7 || username.indexOf(' ') > -1){
usernameFilled = 0;
else{
usernameFilled = 1;
}
}
function email_check(){
email = $('#email').val();
if(email == "" || email.indexOf(' ') > -1) {
emailFilled = 0;
}else{
emailFilled = 1;
}
}
function password_length(){
password = $('#password').val();
if(password == "" || password.indexOf(' ') > -1) {
passwordFilled = 0;
}else{
passwordFilled = 1;
}
}
function password_check(){
password2 = $('#password2').val();
password = $('#password').val();
if(password2.length > 7 && password2 == password) {
password2Filled = 1; /**setting the variable**/
}else{
password2Filled = 0;
}
}
function upload(){
if (usernameFilled == 0 || emailFilled == 0 || passwordFilled == 0 || password2Filled == 0) {
alert('All fields are required');
}else{
/**upload to database**/
}
与其设置全局变量,不如返回 password2Fill 并将其保存在函数外部。然后,您可以将其传递给下一个函数。
即
function password_check(){
password2 = $('#password2').val();
password = $('#password').val();
if(password2.length > 7 && password2 == password) {
password2Filled = 1; /**setting the variable**/
}else{
password2Filled = 0;
}
return password2Filled;
}
function upload(password2Filled)
{
if (password2Filled == 0) { /**calling the variable**/
alert('All fields are required');
}else{
/**upload to database**/
}
}
....
var passwordsOk = password_check();
upload(passwordOk);
尽量避免全局变量,它们会使程序混乱,使难以看到代码流和创建可重用的代码。
您可能以错误的顺序调用函数,或者做错了其他事情,因为它对我来说很好用,稍微编辑了代码以对其进行测试:
function password_check(){
var password2 = $('#password2').val(),
password = $('#password').val();
password2Filled = (password2.length > 7 && password2 == password) ? 1:0;
}
function upload(){
console.log(password2Filled); //prints 0 or 1 just fine ???
}
$("#btn").on('click', function() {
password_check();
upload();
});
小提琴
您可以在 JavaScript 中创建全局变量,方法是在所有函数的范围之外定义它们。这样:
<script type="text/javascript">
var globalVariable;
function blah()
{
globalVariable = "something";
}
function anotherFunction()
{
alert(globalVariable);
}
</script>
ECMAScript/JavaScript 文档指出,"全局对象"应该在任何执行上下文之外创建。