gpt4 book ai didi

javascript - 我如何根据 addEventListener 屁股触发器将两个几乎相同的 javascript 函数写成一个

转载 作者:行者123 更新时间:2023-11-30 18:10:01 25 4
gpt4 key购买 nike

我今天大部分时间都在思考这个问题。我有两种触发同一事件的方法。1. 通过单击输入:文件选择器,或2. 通过将文件拖放到“拖放区”

事件之间的唯一区别是文件 API 使用不同的方法。似乎在 eventListeners 函数调用中唯一允许的参数是 (event)。我可能错过了一些东西,但非常感谢任何帮助

但是复制粘贴几乎相同的代码真的很烦人。有没有办法将“fileSelect(event) 和 dropSelect(event)”这两个函数写成一个?

代码:

function fileSelect(event){

event.stopPropagation();
event.preventDefault();

selectedFile = event.target.files[0]; //Uses ".files" from the file API in HTML5. In this case accessing info on a single file (files[0]).

//Insert file info
document.getElementById('filename').innerHTML = "filename: " + selectedFile.name;
document.getElementById('filetype').innerHTML = "filetype: " + selectedFile.type;
document.getElementById('filesize').innerHTML = "filesize: " + parseFloat(selectedFile.size/1024).toFixed(1) + " kb";
}

//parse the info from a drag'n'drop-selected image. WRITE THESE 2 FUNCTIONS INTO ONE!
function dropSelect(event){

event.stopPropagation();
event.preventDefault();

selectedFile = event.dataTransfer.files[0]; //Uses ".files" from the file API in HTML5. In this case accessing info on a single file (files[0]).

//Insert file info
document.getElementById('filename').innerHTML = "filename: " + selectedFile.name;
document.getElementById('filetype').innerHTML = "filetype: " + selectedFile.type;
document.getElementById('filesize').innerHTML = "filesize: " + parseFloat(selectedFile.size/1024).toFixed(1) + " kb";
}




//add onchange event to the file_select input:file. This will run function "fileSelect", onChange.
document.getElementById('file_select').addEventListener('change', fileSelect, false);

//start fileselect when drag'n'drop.
function handleDragOver(event){
event.stopPropagation();
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
}

document.getElementById('upload_box').addEventListener('dragover', handleDragOver, false);
document.getElementById('upload_box').addEventListener('drop', dropSelect, false);

最佳答案

function select(event){
event.stopPropagation();
event.preventDefault();

selectedFile = (event.dataTransfer || event.target).files[0];

//Insert file info
document.getElementById('filename').innerHTML = "filename: " + selectedFile.name;
document.getElementById('filetype').innerHTML = "filetype: " + selectedFile.type;
document.getElementById('filesize').innerHTML = "filesize: " + parseFloat(selectedFile.size/1024).toFixed(1) + " kb";
}

关于javascript - 我如何根据 addEventListener 屁股触发器将两个几乎相同的 javascript 函数写成一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com