我陷入了一个简单的 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。
最佳答案
您的 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');
}
});
关于javascript - 这个 'else if' 条件不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951328/