javascript - 局部变量的声明

时间:2013-12-17 20:05:18

标签: javascript

我正在使用以下javascript代码..我已经在所有函数启动之前声明了局部变量,但函数在调用时不执行..但是当我用它们的内容替换函数中的所有变量时它只有它工作......我可能做错了什么..我的代码如下......

/* variables */
    var dmv = document.getElementById("dmv").style;
    var nomv = document.getElementById("nomv").style;
    var frsv = document.getElementById("frsv").style;
/* end of variables */

function messagesClick() {
    document.getElementById("notifications").style.visibility = 'visible';
    if (dmv.visibility == 'hidden') {
        dmv.visibility = 'visible';
        nomv.visibility = 'hidden';
        frsv.visibility = 'hidden';
    }else{
            dmv.visibility = 'hidden';
    }
}

function notificationsClick() {
    document.getElementById("notifications").style.visibility = 'visible';
    if (nomv.visibility == 'hidden') {
        nomv.visibility = 'visible';
        dmv.visibility = 'hidden';
        frsv.visibility = 'hidden';
    }else{
            nomv.visibility = 'hidden';
    }
}

function friendRequestClick() {
    document.getElementById("notifications").style.visibility = 'visible';
    if (frsv.visibility == 'hidden') {
        frsv.visibility = 'visible';
        dmv.visibility = 'hidden';
        nomv.visibility = 'hidden';
    }else{
            frsv.visibility = 'hidden';
    }
}

任何帮助将不胜感激..提前感谢.. :))

1 个答案:

答案 0 :(得分:1)

您必须等到元素存在才能访问它们。

您可以等到第一次需要这些值时才能获得它们:

var dmv, nomv, frsv;
var gotStyles = false;

function getStyles() {
    if (!gotStyles) {
        gotStyles = true;
        dmv = document.getElementById("dmv").style;
        nomv = document.getElementById("nomv").style;
        frsv = document.getElementById("frsv").style;
    }
}

function messagesClick() {
    getStyles();
    document.getElementById("notifications").style.visibility = 'visible';
    if (dmv.visibility == 'hidden') {
        dmv.visibility = 'visible';
        nomv.visibility = 'hidden';
        frsv.visibility = 'hidden';
    }else{
            dmv.visibility = 'hidden';
    }
}

function notificationsClick() {
    getStyles();
    document.getElementById("notifications").style.visibility = 'visible';
    if (nomv.visibility == 'hidden') {
        nomv.visibility = 'visible';
        dmv.visibility = 'hidden';
        frsv.visibility = 'hidden';
    }else{
            nomv.visibility = 'hidden';
    }
}

function friendRequestClick() {
    getStyles();
    document.getElementById("notifications").style.visibility = 'visible';
    if (frsv.visibility == 'hidden') {
        frsv.visibility = 'visible';
        dmv.visibility = 'hidden';
        nomv.visibility = 'hidden';
    }else{
            frsv.visibility = 'hidden';
    }
}