【问题标题】:How can I consolidate three functions into one function in order to carry out same functionality?如何将三个功能合并为一个功能以执行相同的功能?
【发布时间】:2020-04-21 06:02:33
【问题描述】:

如果此函数被分成三个单独的函数(一个用于 2 个用于照片,1 个用于视频上传),我有代码可以成功检测文件类型(在用户上传时)。在我的<input/> 标签上,每个输入都有onchange="fileValidation()"。我正在尝试将其合并为一个功能,以便在将其分为三个功能时执行上述成功的功能。

我正在使用香草 JS。一切都在一个页面上。我的猜测是,如果三个单独的输入标签具有相同的fileValidation() 函数,它根本无法正常工作。换句话说 - 如果有人想要上传视频,那么另外两个 <input/> 标签可能会混淆......但我可能错了吗?

我怎样才能将所有这些if()s 合并到一个函数中,这样我就可以让它像分成三个函数那样再次工作?下面的代码供参考。

function fileValidation() {
const realFileBtn = document.getElementById("real-file");
const realFileW9 = document.getElementById("real-file-w9");
const realFileVideo = document.getElementById("real-file-video");

let filePathWinnerPhoto = realFileBtn.value;
let filePathW9 = realFileW9.value;
let filePathVideo = realFileVideo.value;

// Allowing file type
let allowedExtensionsWinnerPhoto = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let allowedExtensionsW9 = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let allowedExtensionsVideo = /(\.mp4|\.mov)$/i;

if (!allowedExtensionsWinnerPhoto.exec(filePathWinnerPhoto)) {
    alert('Invalid file type');
    realFileBtn.value = '';
    return false;
} else {
    console.log("file accepted");
    fileAcceptedFlag = true;
}

if (!allowedExtensionsW9.exec(filePathW9)) {
    alert('Invalid file type');
    realFileW9.value = '';
    return false;
} else {
    console.log("file accepted");
    fileAcceptedW9Flag = true;
}

if (!allowedExtensionsVideo.exec(filePathVideo)) {
    alert('Invalid file type');
    realFileVideo.value = '';
    return false;
} else {
    console.log("file accepted");
    fileAcceptedVideoFlag = true;
}

return fileAcceptedFlag || fileAcceptedW9Flag || fileAcceptedVideoFlag;

【问题讨论】:

  • 将所有三个不同的代码移到同一个函数中并没有什么意义。

标签: javascript function debugging


【解决方案1】:

以下更新包括一个错误变量,用于保存错误并在最后仅返回一次,并在错误存在时发出警报。为了进行测试,我输入了文件名的值并注释掉了输入值的重置。

function fileValidation() {
const realFileBtn = document.getElementById("real-file");
const realFileW9 = document.getElementById("real-file-w9");
const realFileVideo = document.getElementById("real-file-video");

let filePathWinnerPhoto = "test.jp1g";
let filePathW9 = "test.jpxg";
let filePathVideo = "test.mov";

let imgreg = /(\.jpg|\.png|\.HEIC|\.JPEG|\.pdf)$/i;
let videoreg = /(\.mp4|\.mov)$/i;
let errors = [];

if(!imgreg.exec(filePathWinnerPhoto)){
   errors.push("Winner Photo is not valid");
   //realFileBtn.value = "";
}

if(!imgreg.exec(filePathW9)){
   errors.push("W9 Photo is not valid");
   //realFileW9.value = "";
}

if(!videoreg.exec(filePathVideo)){
   errors.push("Video is not valid");
   //realFileVideo.value = "";
}

if(errors.length > 0){
alert(errors.join("\n"));
}
return (errors.length == 0);
}
 fileValidation();

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多