这个'其他如果'条件不起作用

问题描述 投票:1回答:5

我陷入了一个简单的else if状态,并相信这是我第一次遇到这个问题。也许我做错了什么,我不知道。

$('#lblShowCounter').each(function () {
    if ($(this).text() >= '250') {
        alert('red');
    } else if ($(this).text() >= '300') {
        alert('blink');
    } else {
        alert('nothing');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="lblShowCounter">800</span>

问题是这个代码只执行第一个if而不是else if看起来它不会检查元素文本两次,对吧?但是当我使用它时它工作正常:

    $('#lblShowCounter').each(function () {
        if ($(this).text() >= '250') {
            alert('red');
        }
    });

    $('#lblShowCounter').each(function () {
        if ($(this).text() >= '300') {
            alert('blink');
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="lblShowCounter">800</span>

请注意,我想要两个警报,因为800大于300且大于250。

javascript jquery
5个回答
0
投票

由于此问题已更新,表明您需要2个提醒。

使用if/elseif区块,一旦击中第一场比赛,该区块将完成。所以在你的代码中,一旦它与250匹配,if语句就完成了,并且永远不会评估elseif

要获得独立执行的多个条件,它们应该是多个if语句:

$('#lblShowCounter').each(function () {
    var text = $(this).text(),
        matched;

    if (text >= '300') {
        alert('blink');
        matched = true;
    }
    if (text >= '250') {
        alert('red');
        matched = true;
    }

    if (!matched) {
        alert('nothing');
    }
});

3
投票

您的if / else语句的顺序错误。它应该是:

$('#lblShowCounter').each(function () {
    if ($(this).text() >= '300') {
        alert('black');
    } else if ($(this).text() >= '250') {
        alert('blink');
    } else {
    alert('nothing');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="lblShowCounter">800</span>

300大于250,因此第二个语句将永远不会执行,因为对于大于250的所有值(包括大于300),第一个语句为真。

如果你想要执行两个语句,那么你不应该使用else if,因为如果第一个语句为真,它会停止执行。而是使用两个if条款,即:

$('#lblShowCounter').each(function () {
    if ($(this).text() >= '300') {
        alert('black');
    }
    if ($(this).text() >= '250') {
        alert('blink');
    }
});

1
投票

更改订单,因为300大于250

$('#lblShowCounter').each(function () {
    if ($(this).text() >= '300') {
        alert('blink');
    } else if ($(this).text() >= '250') {
        alert('red');
    } else {
    alert('nothing');
    }
});

0
投票

遵循代码的逻辑,没有条件可以在第二个if语句中执行。你必须改变这样的顺序:

$('#lblShowCounter').each(function () {
  if ($(this).text() >= '300') {
    alert('blink');
  } else if ($(this).text() >= '250') {
    alert('red');
  } else {
    alert('nothing');
  }
});

0
投票

尝试使用&&,我的意思是限制持续时间:

$('#lblShowCounter').each(function () {
    if ($(this).text() >= '250' && $(this).text() < '300') {
        alert('red');
    } else if ($(this).text() >= '300') {
        alert('blink');
    } else {
    alert('nothing');
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.