提问者:小点点

检查jQuery中函数是否返回false


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

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

因此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;
    }
});

问题是:脚本停止执行并显示警报消息“Check file not passed”,即使调用的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;
    }
}

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

非常感谢您的任何反馈


共2个答案

匿名用户

只需在函数末尾返回true即可。 如果您不从函数返回任何内容,它将返回undefined,这是一个falsy值。

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;
}

也可以将条件更改为与false完全匹配

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

匿名用户

当所有检查都已通过时,您忘记返回true。

function checkFile(picture) {
    [...previousLines]

    return true;
}