javascript - 检查函数是否在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;
}
}
有没有更好的策略在上传前检查文件?
非常感谢任何反馈
解决方案
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;
}
推荐阅读
- angular - 带有 Angular 6 的 Mapbox。“找不到地图容器”错误
- c - 如果使用空值初始化的结构占用空间
- python - 将文本文件放在另一个位置 - selenium
- c# - 我的 Azure 函数中的“myQueueItem”在触发时产生零值
- ios - 配置文件。“MY BUNDLE ID”不包括签名证书 iPhone 发行版:“我的名字”
- javascript - (帮助) React Native JSON 文件太大。Bundler 堆内存不足
- c++ - 试图创建一个指向动态分配的 char 数组的指针
- macos - mac os ping: ping 必须以 root 身份运行
- sql - 如何在 SQL 中将字符串转换为日期时间
- python - 逐元素应用