简体   繁体   中英

why the variable is working inside the function but not when it is placed outside the function though it has global scope?

i am using this code to change the images on clicking it again and again:

    <!DOCTYPE html>
<head>
    
    <script src="C:\Users\Hp\Desktop\light bulb\js.js"></script>
</head>
<body>

    <div>
        <img id="goku" src="C:/Users/Hp/Desktop/normal goku.png" onclick="goku()">
    </div>
</body>





<!--javascript code-->
let click = 1;
let x = document.getElementById('goku');
function goku() {
    
    switch(click)
    {
        case 1 :
            x.src = "C:/Users/Hp/Desktop/normal goku.png";click++;break;
        case 2 :
            x.src = "C:/Users/Hp/Desktop/super saiyan goku.png";click++;break;
        case 3 : 
        x.src = "C:/Users/Hp/Desktop/super saiyan 3.jpg";click++;break;
        case 4 : 
        x.src = "C:/Users/Hp/Desktop/super saiyan blue.jpg";click=1;break;
    }
}

but it is not working.

And, when i put the let x = document.getElementById('goku'); inside the function, it is working fine. If this is because of the scope of the variable, then it should also applied on click variable but click variable is working fine. Do you have any explanation for this behaviour?

this because your script runs before body content load you can fix it with changing html content like this

<!DOCTYPE html>
<head></head>
<body>
    <div>
        <img id="goku" src="C:/Users/Hp/Desktop/normal goku.png" onclick="goku()">
    </div>
    <script src="C:\Users\Hp\Desktop\light bulb\js.js"></script>
</body>

or you can define x inside the function like this

let click = 1;
function goku(e) {
    let x = e.target
    switch(click)
    {
        case 1 :
            x.src = "C:/Users/Hp/Desktop/normal goku.png";
            click++;
            break;
        case 2 :
            x.src = "C:/Users/Hp/Desktop/super saiyan goku.png";
            click++;
            break;
        case 3 : 
            x.src = "C:/Users/Hp/Desktop/super saiyan 3.jpg";
            click++;
            break;
        case 4 : 
            x.src = "C:/Users/Hp/Desktop/super saiyan blue.jpg";
            click=1;
            break;
    }
}

The script is executed before the img element is added to the document.

If let x = document.getElementById('goku') is outside the function, the element does not exist yet when that line is executed. If it is inside the function, the line is executed when the button is clicked, thus long after the element has been added into the document.

You may move the script tag at the end of <body> (just after </div> ), or wait until the document is ready to call getElementById .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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