加载侦听器上的函数触发得太早

Function on load listener triggered too early

本文关键字:太早 函数 侦听器 加载      更新时间:2023-09-26

iI正在发送XHR请求,并希望用返回的数据在画布上绘制图像,我还希望传递一个索引参数,以便在特定位置绘制图像。

我的问题是,我的函数在传递参数时启动得太快,所以responseText是未定义的。

// Outside loop
function drawSVG(i) {
  svg = this.responseText;
  svgImage = new Image();
  svgImage.src = "data:image/svg+xml," + svg;
  svgImage.load = artboardContext.drawImage(svgImage, i * sliceWidth, i * sliceHeight);
}
// Inside loop
(function(x) {
  var colourReq = new XMLHttpRequest();
  var count = x;
  colourReq.addEventListener("load", function() {
    drawSVG(count);
  }, false);
  colourReq.open("GET", "/color/" + hex);
  colourReq.send();
})(x); 

以下工作,但我不能使用索引[I]来定位svg:

// Inside loop
    (function(x) {
      var colourReq = new XMLHttpRequest();
      var count = x;
      colourReq.addEventListener("load", drawSVG, false);
      colourReq.open("GET", "/color/" + hex);
      colourReq.send();
    })(x); 

我不确定解决这个问题的最佳方法。

responseText未定义,因为您在错误的位置查找它。

this的值取决于函数的调用方式:

drawSVG(count);不会在任何特定对象上调用它,所以您访问的是window.responseText而不是colourReq.responseText

您可以将colourReq作为另一个参数传递:

drawSVG(count, this);

function drawSVG(i, xhr) {
  svg = xhr.responseText;