【问题标题】:Check if function return false in jQuery检查函数是否在jQuery中返回false
【发布时间】:2020-10-07 08:32:20
【问题描述】:

我在尝试检查函数是否返回 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;
    }
}

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

非常感谢您的任何反馈

【问题讨论】:

  • 如果函数末尾不加return true;,会返回undefined,测试为“falsy”。

标签: javascript jquery upload


【解决方案1】:

只需在函数结束时返回true。如果您不从函数返回任何内容,它将返回 undefined,这是一个虚假值。

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

【讨论】:

    【解决方案2】:

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

    function checkFile(picture) {
        [...previousLines]
    
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 2019-12-17
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 2023-03-31
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多