我正在尝试修改一些代码,以便从我在这里找到的浏览器窗口中拖出文件: 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 多个文件。