简体   繁体   中英

Javascript console: Uncaught TypeError: Cannot read property 'style' of null at displaynone

I'm writing a simple javascript slider that is supposed to display a slide, then after 5 secs display:none for that slide, and show the next slide. I get the console error "Uncaught TypeError: Cannot read property 'style' of null at displaynone." Below is the content of the slider7.js:

window.onload = function () {

var imgid = [];

var numberOfSlides = document.getElementById("slide-container").childElementCount;

console.log("total slide count is: " + numberOfSlides);

for (i = 1; i <= numberOfSlides; i++) {
    console.log("here's the value of i: " + i);
    imgid.push("img-" + i);
}

console.log("The full contents of the array are " + imgid);


function displaynone() {
    document.getElementById(imgid[j]).style.display = "none";
}

for (j = 0; j < numberOfSlides; j++) {
    console.log("identify each image id in turn: " + imgid[j]);

    document.getElementById(imgid[j]).style.display = "block";

        window.setTimeout(displaynone, 5000);
    }

};

I wrapped the slider guts within window.onload to ensure all html objects are fully loaded. I've also checked the HTML to ensure that the element IDs I'm styling exist:

<body>
    <div id="slide-container">
        <img id="img-1" src="005.jpg">
        <img id="img-2" src="006.jpg">
        <img id="img-3" src="007.jpg">
        <img id="img-4" src="008.jpg">
        <img id="img-5" src="009.jpg">
    </div>
    <script src="slider7.js"></script>
</body>

Relevant portions of console.log read:

The full contents of the array are img-1,img-2,img-3,img-4,img-5
identify each image id in turn: img-1
identify each image id in turn: img-2
identify each image id in turn: img-3
identify each image id in turn: img-4
identify each image id in turn: img-5

An observation is that the line of code below only generates the console error when wrapped in the window.setTimeout function:

document.getElementById(imgid[j]).style.display = "none";

If I remove this line from the function and simply put it below the line containing ' display ="block" ', it sets the inline display to none, but without any time delay. Thanks for any insights!

simply check out variable j it's undefined in displaynone function. use closure!

Passing parameters into a closure for setTimeout

+added

or you can solve it as declaring variable j as global

Without using windows.onload try to execute the js fucntion like this way.

<body onload="your function">

use css to hide all the images in initial stage.

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