2

我有一个表格,人们可以在其中输入文件路径。我想确保他们进入的路径指向图片,所以这就是我认为可行的方法。

function checkExt()
{
    var extension= /* I know that the code to cut the extension off of the file
                      is working correctly so for now let's just go with it ok */
    if(extension!="jpg" || "gif" || "bmp" || "png" || "whatever else")
        alert("The file extension you have entered is not supported");
}

但这不起作用。我已将其跟踪到 if 语句,因为如果我只选择一种文件进行检查,那么它将正常工作。所以我问你的问题是,我到底要改变什么才能让这件事正常工作。我已经做了大约三个小时了,这让我发疯了。感谢您提前提供的所有帮助。

4

6 回答 6

6

这是语法和逻辑错误。它应该是:

if (extension != "jpg" && 
    extension != "gif" && 
    extension != "bmp" && 
    extension != "png" && 
    extension != "whatever else") {
    // This will execute when the extension is NOT one of the expected 
    // extensions.
}

此外,您可以使用正则表达式更简洁地处理它:

if (!/jpg|gif|bmp|png|whatever/.test(extension)) {
    // This will execute when the extension is NOT one of the expected 
    // extensions.
}

附录:

extension当 的值不是支持的值之一,上面的示例执行 if 语句的主体。如果您想在值为extensions支持的值之一时执行 if 语句的主体,您可以将逻辑从不等于/和更改为等于/或,如下所示:

if (extension == "jpg" || 
    extension == "gif" || 
    extension == "bmp" || 
    extension == "png" || 
    extension == "whatever else") {
    // This will execute when the extension is one of the expected extensions.
}

同样,使用正则表达式会更简洁:

// I just removed the leading ! from the test case.
if (/jpg|gif|bmp|png|whatever/.test(extension)) {
    // This will execute when the extension is one of the expected extensions.
}
于 2012-08-06T21:20:54.907 回答
1

您应该使用&&而不是,||并且必须在每个条件上为!=运算符添加前缀extension,而不仅仅是第一个条件:

if (extension != "jpg" &&
    extension != "gif" &&
    extension != "bmp" && 
    extension != "png" &&
    extension != "whatever else")
于 2012-08-06T21:19:52.160 回答
1

作为冗长的替代方法,使用正则表达式:

if (extension.search(/jpg|gif|bmp|png/) === -1) {
    alert("The file extension you have entered is not supported.");
}
于 2012-08-06T21:25:37.733 回答
0

您需要在每个子句中包含要比较的参数。

if( extension != "jpg" || 
    extension != "gif" || 
    extension != "bmp" || 
    extension != "png" || 
    extension != "whatever else"){
 //TODO: handle condition
}

正如其他人所指出的,这是一个逻辑错误,因为如果“jpg”是扩展名,则条件仍然会被命中,因为“jpg”!=“gif”。您可能要考虑使用&&.

于 2012-08-06T21:20:37.667 回答
0

您必须比较extension每个测试扩展的变量。一种紧凑的方法是:

var extension = whatever;
var supportedExtensions = ["jpg","gif","bmp","png",... whatever else];
if (supportedExtensions.indexOf(extension) < 0) alert("Unsupported extension");
于 2012-08-06T21:23:33.953 回答
0

其他答案向您展示了多重比较的 javascript 逻辑是如何错误的。但是,更好的方法是使用这样的 javascript 映射:

function checkExt() {
    var allowedExtensions = {
        "jpg": true, "gif": true, "bmp": true, "png": true, "whatever else":true
    };
    var extension= /* I know that the code to cut the extension off of the file
                      is working correctly so for now let's just go with it ok */
    if (allowedExtensions[extension] !== true) {
        alert("The file extension you have entered is not supported");
    }
}

只需向对象添加/删除项目即可更容易维护allowedExtensions

于 2012-08-06T21:51:28.327 回答