JavaScript 在没有警报的情况下中断

JavaScript breaks without alert

本文关键字:情况下 中断 有警 JavaScript      更新时间:2023-09-26

遇到JavaScript问题,无法弄清楚为什么代码在onload函数之后包含警报时有效,以及为什么删除警报时它不起作用。

var jsonObjects = [];
var imagesObj = {};
var kinImages = [];
var stage;
var layer = new Kinetic.Layer();
window.onload = function () {
    var jsonloaded;
    $.getJSON('net.json', function (response) {
        jsonloaded = response;
        $.each(jsonloaded, function (key, val) {
            jsonObjects.push(val);
        });
        setupJsonImages();
    });
}
function setupJsonImages() {
    stage = new Kinetic.Stage({
        container: 'container',
        width: 1000,
        height: 800
    });
    for (var i = 0; i < jsonObjects.length; i++) {
        var objName = jsonObjects[i].name;
        imagesObj[objName] = new Image();
        kinImages[i] = new Kinetic.Image({
            image: imagesObj[objName],
            x: jsonObjects[i].x,
            y: jsonObjects[i].y,
            name: jsonObjects[i].name,
            width: 0,
            height: 0,
            draggable: true
        });
        imagesObj[objName].src = jsonObjects[i].img;
        imagesObj[objName].onload = function () {
            layer.add(kinImages[i]);
            layer.draw();
        }
        // if this alert is removed, the code breaks
        alert("imagesobj src");
        kinImages[i].on('dragend', function () {
            $.ajax({
                type: "POST",
                url: 'receiver.php',
                contentType: 'application/json; charset=utf-8',
                async: false,
                data: JSON.stringify({
                    objectname: (this).getName(),
                    xcoord: (this).getPosition().x,
                    ycoord: (this).getPosition().y
                })
            });
        });
    }
    stage.add(layer);
    stage.draw();
}

已经阅读了有关 Ajax 和异步代码的内容,并且警报会产生延迟,但这没有意义,因为 ajax 代码仅在 dragend 之后调用?

重写并得到了我想要的结果。到目前为止效果相当不错:-)

var jsonObjects = [];
var imagesObj = {};
var kinImages = [];
var stage;
var layer = new Kinetic.Layer();
window.onload = function() {
  $.getJSON('net.json', function(response){
    $.each( response, function( key, val ) {
      jsonObjects.push( val );
    });
    createStage();
  });
}
function createStage() {
  stage = new Kinetic.Stage({
    container: 'container',
    width: 1000,
    height: 800
  });
  setupJsonImages(-1);
}
function setupJsonImages(index) {
  index++;
  var objName = jsonObjects[index].name;
  imagesObj[objName] = new Image();
  imagesObj[objName].src = jsonObjects[index].img;
  imagesObj[objName].onload = function() {
    setupKinetic(index, imagesObj[objName]);
  }
}
function setupKinetic(index, theImage) {
  kinImages[index] = new Kinetic.Image({
    image: theImage,
    x: jsonObjects[index].x,    // 0,
    y: jsonObjects[index].y,   //0
    name: jsonObjects[index].name,
    width: 0,
    height: 0,
    draggable: true
  });
  layer.add(kinImages[index]);
  layer.draw();
  kinImages[index].on('dragend',function() {
    $.ajax({
      type: "POST",
      url: 'receiver.php',
      contentType: 'application/json; charset=utf-8',
      async: true,
      data: JSON.stringify({ 
        objectname:(this).getName(), 
        xcoord: (this).getPosition().x, 
        ycoord : (this).getPosition().y 
      })
    });
  });
  if(index < jsonObjects.length -1) {
    setupJsonImages(index);
  }
  else {
    finishStage();
  }
}
function finishStage() {
  stage.add(layer);
  stage.draw();
}  

在代码方面可能不是最优雅的解决方案,但它可以工作并满足 atm 需求。感谢所有海报的投入。

这个怎么样:

window.onload = function() {  
    $.getJSON('net.json', function(){ 
        console.log('it worked');
    }).done(function(response){
        $.each( response, function( key, val ) {
            jsonObjects.push( val );
        });
    });
}

setupJsonImages函数中,此代码将图像添加到图层:

imagesObj[objName].onload = function() {
  layer.add(kinImages[i]);
  layer.draw();
}

在此代码中,i 的值通常会jsonObjects.length,因为i的作用域为 setupJsonImages 函数,并且在 onload 执行时,for 循环已完成。 警报语句将i值固定在当前值,因为停止使其工作。

尝试用这个替换你的 for 循环:

for( var i=0; i<jsonObjects.length; i++) {
    var objName = jsonObjects[i].name;
    imagesObj[objName] = new Image();
    imagesObj[objName].src = jsonObjects[i].img;
    // hook up the data we need in the onload event
    var $imgObj = $(imagesObj[objName]);
    $imgObj.data({
        x: jsonObjects[i].x,
        y: jsonObjects[i].y,
        name: jsonObjects[i].name
    });
    imagesObj[objName].onload = function() {
        var $this = $(this);
        var kinImg = new Kinetic.Image({
            image: this, // this = the loaded image
            x: $this.data('x'),
            y: $this.data('y'),
            name: $this.data('name'),
            width: 0,
            height: 0,
            draggable: true
        });
        kinImg.on('dragend',function() {
            $.ajax({
                type: "POST",
                url: 'receiver.php',
                contentType: 'application/json; charset=utf-8',
                async: false,
                data: JSON.stringify({ objectname:(this).getName(), xcoord: (this).getPosition().x, ycoord : (this).getPosition().y })
            });
        });
        kinImages.push(kinImg);
        layer.add(kinImages);
        layer.draw();
    };
}