循环中的javascript onload事件

时间:2014-02-16 11:56:52

标签: javascript jquery loops asynchronous onload

我正在尝试遍历json图像数组,将图像添加到地图上的标记。由于javascript是异步的,它导致我出现问题,我想在将图像添加到我的地图之前等待图像加载,并且在循环结束之前无法加载我的图像。这是否有可能实现,因为我试图用回调实现,但无法使其工作。

 for (var i = 0; i < jsonObj.potholes.length; i++)
 {  
      var image = new Image();



                image.src = "data:image/png;base64," + jsonObj.potholes[i].image;
                image.onload = function()
                {
                    //alert("image loaded");
                    EXIF.getData(image, function()
                    {
                        otn = parseInt(EXIF.getTag(image, "Orientation"));
                        dataURL = drawCanvas(otn, image).toDataURL();

                        var circle = L.circle([jsonObj.potholes[i].lat, jsonObj.potholes[i].lon], 18, {
                            color: 'yellow',
                            fillColor: 'red',
                            fillOpacity: 0.5
                        }).addTo(markersLayerGroup).bindPopup("Pothole ID " + jsonObj.potholes[i].id
                                + "<br />Location " + city[i] + "," + street[i] +
                                "<image src = '" + dataURL + "'></image>");


                    });



}

2 个答案:

答案 0 :(得分:1)

您应该实现异步循环(使用if):

(function (ondone) {
    var index = 0;
    nextStep();

    function nextStep() {
        if (index >= jsonObj.potholes.length) {
            if (ondone)
                ondone();
            return;
        }

        var i = index++;
        var image = new Image();

        image.src = "data:image/png;base64," + jsonObj.potholes[i].image;
        image.onload = function () {
            //alert("image loaded");
            EXIF.getData(image, function () {
                otn = parseInt(EXIF.getTag(image, "Orientation"));
                dataURL = drawCanvas(otn, image).toDataURL();

                var circle = L.circle([jsonObj.potholes[i].lat, jsonObj.potholes[i].lon], 18, {
                    color: 'yellow',
                    fillColor: 'red',
                    fillOpacity: 0.5
                }).addTo(markersLayerGroup).bindPopup("Pothole ID " + jsonObj.potholes[i].id
                        + "<br />Location " + city[i] + "," + street[i] +
                        "<image src = '" + dataURL + "'></image>");

                nextStep();
            });
        }
    }
})(function () { alert("Done!"); });

你也可以使用Promises,例如:JavaScript: Async Promise "while loop"

答案 1 :(得分:0)

希望现在还为时不晚。还有另一个更简单的解决方案 - 将所有内容都抛到另一个函数中。

 $('#example').DataTable( {
				"scrollY":        "500px",
				"scrollCollapse": true,
				"paging": true,
				"lengthChange": false,
				"searching": true,
				"ordering": true,
				"info": true,
				"bDestroy": true,
				"autoWidth": true,
				"aLengthMenu": [[-1], ["All"]],
    });
				
			$('#example').dataTable().fnDestroy();