首页 > 解决方案 > 如何为 IE 正确使用 onchange 元素

问题描述

对于上传文件,我使用这种形式:

<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
  <div id="drag_upload_file">                                               
    <p>DROP FILE(S) HERE</p>
    <p>or</p>

    <p><input class="browse btn" type="button" id="browse" value="Browse" onclick="file_explorer();"></p>
    <input type="file" id="selectfile" name="upload" multiple>

   </div>
</div>

js的这一部分

 function file_explorer() {

        document.getElementById('selectfile').click();
        document.getElementById('selectfile').onchange = function() {
            for (var i=0; i< this.files.length;i++){ // multiple files uploading
              fileobj = document.getElementById('selectfile').files[i];
              ajax_file_upload(fileobj);
            }
        };

    }

上传在所有浏览器中都有效,除了 IE。我已经发现 IE 和onchange.

有没有办法可以重写该函数file_explorer,使其在 IE 中也能正常工作?

标签: javascriptjqueryinternet-exploreruploadonchange

解决方案


尝试使用 JavaScript 方法附​​加 ondrop 功能,请修改您的代码如下:

<head>
    <meta charset="utf-8" />
    <title></title>
    <script>
        function myFunction() {
            document.getElementById('selectfile').ondrop = function () {                    
                document.getElementById('selectfile').click();
                document.getElementById('selectfile').onchange = function () {
                    for (var i = 0; i < this.files.length; i++) { // multiple files uploading
                        fileobj = document.getElementById('selectfile').files[i];
                        //ajax_file_upload(fileobj);
                    }
                };
            };
        };
    </script>
</head>
<body onload="myFunction()">
    <div id="drop_file_zone" ondragover="return false">
        <div id="drag_upload_file">
            <p>DROP FILE(S) HERE</p>
            <p>or</p>

            <p><input class="browse btn" type="button" id="browse" value="Browse" onclick="file_explorer();"></p>
            <input type="file" id="selectfile" name="upload" multiple>

        </div>
    </div>
</body>

推荐阅读