简体   繁体   中英

using onload and onerror javascript

function loadNextComic()
{
window.scrollTo( 200, 480);
img comic = new Image();
    currentComicNumber++;
    comic.src="Freqpg"+currentComicNumber+".jpg";
    comic.onload = function()
        {
        document.getElementById("comic").src="Freqpg"+currentComicNumber+".jpg";
        document.getElementById("numberOutput").innerHTML=currentComicNumber;
        }
    comic.onerror =lastComicReached();


}

This code is intended to iterate a webcomic page. If the next page exists, it should load, and once loaded, display. If the page doesn't exist, the code should call another function, as this indicates we have probably reached the end of the archive. Unfortunately, this code does nothing at all. Even the scroll function breaks.

function loadNextComic()
{
window.scrollTo( 200, 480);
//img comic = new Image();
    currentComicNumber++;
    //comic.src="Freqpg"+currentComicNumber+".jpg";
    //comic.onload = function()
    //  {
        document.getElementById("comic").src="Freqpg"+currentComicNumber+".jpg";
        document.getElementById("numberOutput").innerHTML=currentComicNumber;
    //  }
    //comic.onerror =lastComicReached();


}

This code with the img code commented out progresses the pages correctly until of course I run out of pages (which are consecutively and reliably named), and seeing as how this number will change weekly, I can't simply hard code the last page number. I tried using the img.onerror and onload code after looking at other examples on the site. Clearly I've been fumbling like an idiot with this. I've read in a few places about asynchronous execution breaking onerror, but I thought this should have accounted for that.

How do I get the img.onload and onerror functions to work? How do you do structured programming if the code executes asynchronously?

You need to declare them BEFORE you change the src

Also you are REPLACING the onerror, and therefore you need to remove the () unless lastComicReached returns a function

Lastly img comic is not valid syntax, you mean var comic

var comic = new Image(); 
comic.onload = function() {
  document.getElementById("comic").src="Freqpg"+currentComicNumber+".jpg";
  document.getElementById("numberOutput").innerHTML=currentComicNumber;
}
comic.onerror =lastComicReached; // remove the () here!!
comic.src="Freqpg"+currentComicNumber+".jpg";

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