有一个 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 之后调用?