首页 > 解决方案 > 在 Javascript 中,如何在继续其余过程之前先执行 image.onload 函数

问题描述

下面是我执行的代码:

    <head>
        <script>
            function uploadFile() {
                console.log('here');
                var x = document.getElementById('img');
                console.log(x.files);

                var _URL = window.URL || window.webkitURL;
                var file = x.files.item(0);
                var img = new Image();
                img.src = _URL.createObjectURL(file);
                img.onload = function () {
                    alert("alert1 : this alert should come before");
                    alert(this.width + " " + this.height);
                }
                alert("alert2: this alert should come later");
            }
        </script>
    </head>
    <body>
        <input type='file' id='img' accept="image/*"/>
        <input type='submit' value='Upload' onclick='uploadFile()'/>    
    </body>
<html>

我希望alert1在alert2之前显示。

目前,第一个 alert2 显示在 alert1 之前。

标签: javascripthtmlfile-uploadcallback

解决方案


文档如何image.onload说:

当图像完成加载时,将在图像元素上调用此事件处理程序

似乎在执行第二个警报之前没有加载图像。您可以检查图像是否已加载,然后以您的方式处理它。


推荐阅读