使用javascript从浏览器中拖出文件

时间:2013-06-04 14:13:55

标签: javascript arrays google-chrome variables for-loop

我正在尝试修改一些代码,用于从我在此处找到的浏览器窗口中拖出文件: http://www.thecssninja.com/javascript/gmail-dragout

在我的代码中,我想使用for循环,这样我就可以处理大量文件而无需反复重复代码。

这就是我所拥有的:

<a href = "file0" id = "0" draggable = "true" data-downloadurl="application/pdf:file0name.pdf:file:///C:/filepath/file0.pdf">file0</a>
<a href = "file1" id = "1" draggable = "true" data-downloadurl="application/pdf:file1name.pdf:file:///C:/filepath/file1.pdf">file1</a>
<a href = "file2" id = "2" draggable = "true" data-downloadurl="application/pdf:file2name.pdf:file:///C:/filepath/file2name.pdf">file2</a>
<a href = "file3" id = "3" draggable = "true" data-downloadurl="application/pdf:file3name.pdf:file:///C:/filepath/file3name.pdf">file3</a>

<script type = "text/javascript>
    var file_count = 3;
var fileDetails = [];

var files = new Array(file_count);
for(var i=0; i<=file_count; i++) {
    files[i] = document.getElementById(i);
}

if(typeof files[0].dataset === "undefined") {
    for (i=0; i<=file_count; i++) {
        fileDetails[i] = files[i].getAttribute("data-downloadurl");
    }
}else {
    for (i=0; i<=file_count; i++) {
        fileDetails[i] = files[i].dataset.downloadurl;
    }
}

//I'm pretty sure the problem starts here.
//If you substitue i for a specific element from the array and comment out the for loop, the script works just fine for the element specified.
for(i=0; i<=file_count; i++) {
    files[i].addEventListener("dragstart",function(evt){
        evt.dataTransfer.setData("DownloadURL",fileDetails[i]);
    },false);
}

我很确定问题从我标记的地方开始,我不确定为什么会出现问题或如何解决问题。

我应该指出一些事情:

此功能仅适用于Chrome。这对我来说不是问题。

我希望这能处理20多个文件。

1 个答案:

答案 0 :(得分:0)

问题确实从您认为的问题开始

//I'm pretty sure the problem starts here.
//If you substitue i for a specific element from the array and comment out the for loop, the script works just fine for the element specified.
for(i=0; i<=file_count; i++) {
    files[i].addEventListener("dragstart",function(evt){
        evt.dataTransfer.setData("DownloadURL",fileDetails[i]);
    },false);
}

基本上你的dragstart事件监听器绑定到i,在执行时它是列表中的最后一个元素。

以下内容会更好。

//I'm pretty sure the problem starts here.
//If you substitue i for a specific element from the array and comment out the for loop, the script works just fine for the element specified.
for(i=0; i<=file_count; i++) {
    files[i].addEventListener("dragstart", (function(idx) {
        return function(evt){
           evt.dataTransfer.setData("DownloadURL",fileDetails[idx]);
        }
    })(i),false);
}

在上面的代码中,您将创建并返回一个类型为function的对象,其中包含正确的i bound值 - 实质上,闭包是在不同的级别创建的,因此在访问时将获得正确的数据。