Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - substr() with negative value not working in IE

EDIT:I've changed the title, because the issue had nothing to do with IE image.load() firing - my substr() wasn't working (see accepted answer).


There's a ton of posts about making sure that you define your onload handler prior to assigning img.src in order to guarantee that the onload handler is in place in case the image is loaded from cache first.

This does not appear to the be issue in my code, since that's precisely what I have done.

Note that this script works across all other browsers, but IE 8 and lower does not trigger the onload inline function.

var i = lastSlideIndex || 1;

while(imagesQueued < MAX_IMAGES){
    var preloadImage = new Image();
    preloadImage.arrayIndex = i;
    preloadImage.onload = function(eventObj){
        debug('Image ' + this.src + ' loaded.');
        slideshowImages[this.arrayIndex] = this;
        if (this.arrayIndex > lastImageIndex) lastImageIndex = this.arrayIndex;
        triggerSlideshow(this.arrayIndex);
    }

    // add leading zeros
    var leadingZeros = "0000000".substr(-(String(MAX_IMAGES).length));
    imageNumber = leadingZeros.substr(String(i).length) + i;

    debug('preloading Image #' + imageNumber);
    preloadImage.src = fullImagePrefix + imageNumber + "." + IMAGES_TLA;

    if (++i > MAX_IMAGES) i = 1;
    imagesQueued++;
}

Any other suggestions would be deeply appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Now that this question is retitled to be about substr() in IE 8, here's the quick fix to the negative index problem. Paste the following code from Mozilla Developer Network:

// only run when the substr() function is broken
if ('ab'.substr(-1) != 'b') {
  /**
   *  Get the substring of a string
   *  @param  {integer}  start   where to start the substring
   *  @param  {integer}  length  how many characters to return
   *  @return {string}
   */
  String.prototype.substr = function(substr) {
    return function(start, length) {
      // call the original method
      return substr.call(this,
        // did we get a negative start, calculate how much it is from the beginning of the string
        // adjust the start parameter for negative value
        start < 0 ? this.length + start : start,
        length);
    }
  }(String.prototype.substr);
};

This code detects the broken implementation of substr and replaces it with a compliant one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...