具有负值的substr()在IE中不起作用

Tom*_*ger 6 javascript explorer onload substr slice

编辑:我已经改变了标题,因为这个问题与IE无关.image.load()触发 - 我的substr()无法正常工作(参见接受的答案).


关于确保在分配img.src之前定义onload处理程序有很多帖子,以确保在首先从缓存加载图像的情况下onload处理程序就位.

这似乎不是我的代码中的问题,因为这正是我所做的.

请注意,此脚本适用于所有其他浏览器,但IE 8及更低版本不会触发onload内联函数.

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++;
}
Run Code Online (Sandbox Code Playgroud)

任何其他建议将深表感谢!

jos*_*osh 11

现在这个问题substr()在IE 8中被重新命名,这里是负面索引问题的快速解决方法.从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);
};
Run Code Online (Sandbox Code Playgroud)

此代码检测substr的破坏实现,并将其替换为兼容的.


Mrc*_*ief 9

更新:正如评论者指出的那样(我现在不能证明它们),我删除了第一个建议.

还有几点需要注意:

onload如果从缓存加载图像,则不会触发事件.尝试清除缓存并重试.

另一个问题是IE不喜欢负面的substr.slice改为使用:

"0000000".slice(-(String(MAX_IMAGES).length));
Run Code Online (Sandbox Code Playgroud)