【问题标题】:Trouble using the OR operator in a jQuery if statement在 jQuery if 语句中使用 OR 运算符时遇到问题 [关闭]
【发布时间】:2018-04-23 16:33:54
【问题描述】:

我的目标是使用 OR 语句列表检查给定成分的不同属性,但它返回意外 ||错误。

$(".ingredient.clicked").each(function() {
  if (typeof $(this).attr("noAddedSugar") != "undefined") 
      || (typeof $(this).attr("vegan") != "undefined") 
      || (typeof $(this).attr("glutenfree") != "undefined")  
  {
    $('#proba').text("Proba");
  } else {
    $('#proba').text("");
    return false;
  }  
});

当我单独添加和修改变量时它有效,当我使用 OR 时无效。任何意见将不胜感激。

谢谢!

【问题讨论】:

  • 这不是有效的 JS。检查您的控制台是否有错误。
  • 你打开了")"条件,typeof $(this).attr("noAddedSugar") != "undefined") 需要先打开
  • if-syntax is if(expression) not if (expression) || (expression) 所以你需要if ((expression) || (expression))

标签: javascript jquery conditional-statements


【解决方案1】:

您的 if 逻辑需要完全括在一组单独的括号中:

 if ((typeof $(this).attr("noAddedSugar") != "undefined") || (typeof $(this).attr("vegan") != "undefined") || (typeof $(this).attr("glutenfree") != "undefined"))

现在的样子,在第一个!="undefined")之后结束

每个条件周围的内括号不是必需的,因此您可以将其简化为:

if( typeof $(this).attr("noAddedSugar") != "undefined" || typeof $(this).attr("vegan") != "undefined" || typeof $(this).attr("glutenfree") != "undefined" )

【讨论】:

    【解决方案2】:
       if (typeof $(this).attr("noAddedSugar") != "undefined") || (typeof $(this).attr("vegan") != "undefined") || (typeof $(this).attr("glutenfree") != "undefined") 
    

    应该是

    if( (typeof $(this).attr("noAddedSugar") != "undefined") || (typeof $(this).attr("vegan") != "undefined") || (typeof $(this).attr("glutenfree") != "undefined")  )
    

    【讨论】:

    • 关于答案的快速问题。如果我使用此代码 - if( (typeof $(this).attr("vegan") != "undefined") || (typeof $(this).attr("glutenfree") != "undefined") || (typeof $(this).attr("vegetarian") != "undefined") ) { $('#diettext').text("ALAPSZÓSZ NÉLKÜL KÉRD!"); } 其他 { $('#diettext').text(""); $('#diettext').fadeTo(1000, 0);语句的 IF 部分效果很好,但无论我做什么,我都无法让 else 部分发挥作用。你介意看看吗? codepen.io/Pbalazs89/full/LOjqQM
    猜你喜欢
    • 2017-03-06
    • 2014-02-17
    • 2017-03-07
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多