开发者

Group multiple or statements within an IF in javascript

The following code works:

$(".valClear").each(function () {
        if ($(this).val().indexOf(".png") == -1) {
            $(this).val('');
        }
    });

However this doesn't (the value is removed even if it contains .png or .jpeg), what am I doing wrong?

$(".valClear").each(function () {
        if (($(this).val().indexOf(".png") 开发者_如何转开发== -1) || ($(this).val().indexOf(".jpeg") == -1)) {
            $(this).val('');
        }
    });


You're doing an OR, seems like you want an AND, like this:

$(".valClear").each(function () {
    if (($(this).val().indexOf(".png") == -1) && ($(this).val().indexOf(".jpeg") == -1)) {
        $(this).val('');
    }
});

With your OR logic, the value will likely not have either one of them, and the other part will be true, you want an AND, meaning it has neither in the value.

You can also optimize it a bit, like this:

$(".valClear").each(function () {
  var val = $(this).val();
  if ((val.indexOf(".png") == -1) && (val.indexOf(".jpeg") == -1)) {
    $(this).val('');
  }
});

To stray quite a bit from the question, and towards your actual problem...I'd actually change up how you're doing this, using an array of allowed extensions and $.inArray() to check it, like this:

var allowedExtensions = ["png", "jpeg", "bmp"];
$(".valClear").each(function () {
  if ($.inArray($(this).val().split('.').pop(), allowedExtensions) == -1) {
    $(this).val('');
  }
});

You can test it here. You can see from the format, this is much easier to expand to allow additional extensions later.


You have to use AND:

($(this).val().indexOf(".png") == -1) && ($(this).val().indexOf(".jpeg") == -1)

If the the string ends in .jpeg then the first expression will evaluate to true.
true OR false == true (the second expression won't even get evaluated).

Another option is to negate the whole expression (and test for whether .png and .jpeg are contained rather than not contained):

!($(this).val().indexOf(".png") > -1) || ($(this).val().indexOf(".jpeg") > -1))


Think of that second if test. It's like saying this:

If what you offer me for dinner is not roast chicken or it is not cold ham, then I'll have some

In that situation, you might get some cold ham or you might get roast chicken. Why? Because roast chicken is not cold ham, and because cold ham is not roast chicken. You said you're OK with whatever the kitchen has ready as long as what you get is either not roast chicken or not cold ham, so either of the two satisfies the condition.

If you phrase the qualifier with and instead of or, of course, then the kitchen will have to get creative with the left-over mashed potatoes.


Here's an alternative for and/or conditions. If the value doesn't match the regexp then..

$(".valClear").each(function () {
  if ( !$(this).val().match(/\.(png|jpeg)/) ) {
    $(this).val('');
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜