jQuery - 如果Else语句不起作用,但如果分成单独的if语句则有效 [英] jQuery - If Else statement not working but works if separated into individual if statements

查看:570
本文介绍了jQuery - 如果Else语句不起作用,但如果分成单独的if语句则有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码仅适用于 if语句,后续 else if语句不会触发。但如果我将所有3个分成单独的 if语句一切正常。如何让他们一起玩得很好?

The code below only works for the if statement, the subsequent else if statements do not fire. But if I separate all 3 into individual if statements everything works fine. How can I make them all play nice together?

不工作

  if ( headingLength < 1 ) {
    // show error message
    $('.compose-wrap .message-heading .help-block').fadeIn();
  } else if ( messageLength < 1 ) {
    // show error message
    $('.compose-wrap .message-body .help-block').fadeIn();
  } else if ( formtagLength < 1 ) {
    // show error message
    $('.compose-wrap .choose-recipients .help-block').fadeIn();
  }

工作

  if ( headingLength < 1 ) {
    // show error message
    $('.compose-wrap .message-heading .help-block').fadeIn();
  }

  if ( messageLength < 1 ) {
    // show error message
    $('.compose-wrap .message-body .help-block').fadeIn();
  }

  if ( formtagLength < 1 ) {
    // show error message
    $('.compose-wrap .choose-recipients .help-block').fadeIn();
  }


推荐答案

听起来好像在跑步你的否则当你不想要的时候。如果解决了前一个条件中的任何一个,则条件退出,这是预期的行为。

It sounds as if your running your else if when you dont want to. If any one of the former conditions are solved the condition exits, this is expected behaviour.

回答
如果您的底部有什么东西没有运行,那么您可能不会如果想要那个部分在其他内部。如果你需要仔细检查逻辑比较运算符,如果你确实需要在else中使用它。例如> > = === == != < = < && 等。切换它们直到你有你想要的东西。

Answer: If you have something on the bottom thats not running which you expect to be running, then you probably don't want that part inside an else if. If you do need it in the else if you need to carefully check your logic comparison operators. e.g. the > >= === == != <= < && etc.. switch them around until you have what you want.

您也可以将它们合并,例如

You can also combine them, e.g.

if ( headingLength < 1 ) {
    // show error message
    $('.compose-wrap .message-heading .help-block').fadeIn();
} else if ( (messageLength < 1) && headingLength >=1 ) {
    // show error message
    $('.compose-wrap .message-body .help-block').fadeIn();
} else {
    console.log('wasnt one of the above yet, rinse and repeat...');
}

此外,最好还是以其他方式结束,也许还有控制台记录,直到你拨入。

Also, its best to end with a final else also, maybe with a console log, until you get it dialed in.

这篇关于jQuery - 如果Else语句不起作用,但如果分成单独的if语句则有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆