javascript

时间:2016-10-21 09:33:18

标签: javascript

我对编码非常陌生,我试图理解局部和全局变量之间的区别。我试图创建一个图像库,您可以通过按下按钮切换图像。我通过将图像变量作为局部变量放在函数中来实现它。但是,如果我把它作为一个全局变量放在函数之外,它将无法工作。那是为什么?

这是我的HTML:

<button onclick="previous_image();"></button>
<img src="image1.jpg" alt="Image gallery" id="image"/>
<button onclick="next_image();"></button>

当我开始工作时,这是我的Javascript:

var image_tracker = "a";

function previous_image(){
    var image = document.getElementById("image");
    switch(image_tracker){
        case("a"): 
            image.src = "image3.jpg";
            image_tracker = "c";    
            break;

        case("c"): 
            image.src = "image2.jpg";
            image_tracker = "b";    
            break;

        case("b"): 
            image.src = "image1.jpg";
            image_tracker = "a";    
            break;
    }

}

function next(){
    var image = document.getElementById("image");
    switch(image_tracker){
        case("a"): 
            image.src = "image2.jpg";
            image_tracker = "b";    
            break;

        case("b"): 
            image.src = "image3.jpg";
            image_tracker = "c";    
            break;

        case("c"): 
            image.src = "image1.jpg";
            image_tracker = "a";    
            break;
    }

}

这是我的javascript,当它没有工作时:

var image_tracker = "a";
var image = document.getElementById("image"); 

function previous_image(){
    switch(image_tracker){
        case("a"): 
            image.src = "image3.jpg";
            image_tracker = "c";    
            break;

        case("c"): 
            image.src = "image2.jpg";
            image_tracker = "b";    
            break;

        case("b"): 
            image.src = "image1.jpg";
            image_tracker = "a";    
            break;
    }

}

function next(){
    switch(image_tracker){
        case("a"): 
            image.src = "image2.jpg";
            image_tracker = "b";    
            break;

        case("b"): 
            image.src = "image3.jpg";
            image_tracker = "c";    
            break;

        case("c"): 
            image.src = "image1.jpg";
            image_tracker = "a";    
            break;
    }

}

2 个答案:

答案 0 :(得分:1)

使用类似的东西:

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

答案 1 :(得分:0)

我认为你的第二个代码无法工作的原因是因为这一行

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

在加载DOM之前运行。

如果您需要使用普通的javascript,可以在myFunction中添加该行

body onload="myFunction()"

在加载DOM后加载。