JQuery文件输入类型无法识别

时间:2015-11-10 15:42:12

标签: jquery

我想了解一些事情。如果我做以下

 if( $("#fileOne")[0].files[0].type != 'application/pdf') {
        errors.push("- Please upload correct document type");
    }

它可以正常工作......如果我不上传PDF,我会收到错误,如果我这样做,我就不会收到错误。但是,如果我将其更改为以下

if(  $("#fileOne")[0].files[0].type != 'image/bmp' ||
            $("#fileOne")[0].files[0].type != 'image/jpeg' ||
            $("#fileOne")[0].files[0].type != 'image/pjpeg' ||
            $("#fileOne")[0].files[0].type != 'image/png' ||
            $("#fileOne")[0].files[0].type != 'image/tiff' ||
            $("#fileOne")[0].files[0].type != 'application/pdf') 
{
    errors.push("- Please upload one of the valid document types");
}

如果我上传PDF或其中列出的任何其他文件,它仍然会抛出错误。似乎添加所有额外的类型似乎使它失败。

这有什么理由吗?

由于

3 个答案:

答案 0 :(得分:2)

看看你的逻辑:

  

如果它不是位图,或者它不是JPEG

如果 是位图,则不是 JPEG,反之亦然。

你的情况永远不会成真。

你想要AND测试而不是OR测试。

答案 1 :(得分:1)

你必须使用OR的内容:

if(  $("#fileOne")[0].files[0].type != 'image/bmp' &&
            $("#fileOne")[0].files[0].type != 'image/jpeg' &&
            $("#fileOne")[0].files[0].type != 'image/pjpeg' &&
            $("#fileOne")[0].files[0].type != 'image/png' &&
            $("#fileOne")[0].files[0].type != 'image/tiff' &&
            $("#fileOne")[0].files[0].type != 'application/pdf') 
{
    errors.push("- Please upload one of the valid document types");
}

答案 2 :(得分:-1)

使用&&而不是||:

var ftype = $("#fileOne")[0].files[0].type;
if( ftype != 'image/bmp' && 
    ftype != 'image/jpeg' &&
    ftype != 'image/pjpeg' &&
    ftype != 'image/png' &&
    ftype != 'image/tiff' &&
    ftype != 'application/pdf') {
    errors.push("- Please upload one of the valid document types");
}
相关问题