为什么javascript不能识别我的全局变量?

时间:2015-07-06 20:39:50

标签: javascript variables global

我正在设置一个等于图像的变量,然后在函数中调用它。 这不起作用,因为根据javascript错误控制台,它不会将图像变量识别为null

var image = document.getElementById("gc");
var duration = 3000; /* fade duration in millisecond */
var hidtime = 2000; /* time to stay hidden */
var showtime = 2000; /* time to stay visible */
var image_tracker = 1

function change() {
    if (image_tracker == 1) {
        image.src = "IMG_1267.jpg"
        image_tracker = 2
    } else if (image_tracker == 2) {
        image.src = "IMG_1239.jpg"
        image_tracker = 3
    } else {
        image.src = "IMG_1263.jpg"
        image_tracker = 1
    }
}

然而这很好用

var duration = 3000; /* fade duration in millisecond */
var hidtime = 2000; /* time to stay hidden */
var showtime = 2000; /* time to stay visible */
var image_tracker = 1

function change() {

    var image = document.getElementById("gc");

    if (image_tracker == 1) {

        image.src = "IMG_1267.jpg"
        image_tracker = 2
    } else if (image_tracker == 2) {
        image.src = "IMG_1239.jpg"
        image_tracker = 3
    } else {

        image.src = "IMG_1263.jpg"
        image_tracker = 1
    }

}

var timer = setInterval('change()', 3000);

1 个答案:

答案 0 :(得分:6)

在您的代码中,即使在DOM完全加载之前,您的JavaScript也会立即加载。当它尝试搜索#gc时,它无法找到它,因为它没有加载到DOM中。

解决方案是在页面完全加载时设置image变量。离。

var image;

window.onload = function() {
    image = document.getElementById("gc");
}

function change() {
    ....