首页 > 解决方案 > 检查函数是否在jQuery中返回false

问题描述

我在尝试检查函数是否返回 false 时遇到了麻烦。

当用户在输入表单字段中选择文件时,我正在编写一个脚本来上传图片文件。

所以html表单如下:

<form enctype="multipart/form-data" id="upload-form" role="form">
<input type="hidden" id="register-id" name="id" value="">
<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <label>Select image</label>
            <div class="custom-file">
                <input type="file" name="filedata" class="custom-file-input" id="picture" accept="image/*">
                <label class="custom-file-label" for="picture">Choose file</label>
            </div>
        </div>
        <div class="progress mb-2 progress-sm">
            <div id="file-progress-bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>
    </div>
</div>
</form>

在输入更改时获取文件的javascript代码如下,代码应该开始一些文件检查

$('#picture').on('change', function() {
    let picture = this.files[0];

    if(!checkFile(picture)) {
        alert("Check file not passed");
        return false;
    }
});

问题是:脚本停止执行并显示警告消息“检查文件未通过”,即使调用的 checkFile 函数没有返回 fasle,因为文件通过了所有检查。怎么了?非常感谢。

在 checkFile 函数下面

function checkFile(picture) {
    let imagetype = picture.type;
    console.log('Picture type ' + imagetype);
    let match= ["image/jpeg","image/png","image/jpg"];
    if(!((imagetype==match[0]) || (imagetype==match[1]) || (imagetype==match[2])))
    {
        console.log('Matching picture type failed');
        return false;
    }

    let reg=/(.jpg|.gif|.png)$/;
    console.log('Picture name is ' + picture.name);
    if (!reg.test(picture.name)) {
        console.log('Check picture name failed');
        return false;
    }
    console.log('Picture size is ' + picture.size);
    if (picture.size > 204800) {
        console.log('Check picture size failed');
        return false;
    }
}

有没有更好的策略在上传前检查文件?

非常感谢任何反馈

标签: javascriptjqueryupload

解决方案


Just return true at the end of your function. If you will not return anything from the function it will return undefined which is a falsy value.

function checkFile(picture) {
  let imagetype = picture.type;

  // ... rest of the code

  if (picture.size > 204800) {
    console.log('Check picture size failed');
    return false;
  }
  return true;
}

Or you can change the condition to match exactly with false

if(checkFile(picture) === false) {
  alert("Check file not passed");
  return false;
}

推荐阅读