【问题标题】:Ternary operation JS not working三元运算符 JS 不起作用
【发布时间】:2015-01-19 15:54:29
【问题描述】:

我尝试这样做:

$('#hire_button').html(data.code == 500 ?  "<span class='alert alert-danger>" : "<span class='alert alert-success>" + data.info + "</span>");

但它返回或success&gt; 或空行。我做错了什么?

【问题讨论】:

  • 只需在三元组周围加上括号。我怀疑您有运算符优先级问题。
  • 三元运算符正在工作……

标签: javascript ternary-operator


【解决方案1】:

? : 三元运算符的优先级低于+ 串联运算符,因此您构建的标签不匹配。

但是,恕我直言,您应该重构代码以避免一些重复,同时自动修复优先级问题:

$('#hire_button').empty().append($('<span>', text: data.info, class: 'alert'})
   .addClass(data.code == 500 ? 'alert-danger' : 'alert-success'));

注意:上面重写为原始错误地将新类添加到按钮而不是封闭的跨度。

【讨论】:

    【解决方案2】:

    + 的运算符优先级高于三元运算符。把他们分组清楚。

    $('#hire_button').html((data.code == 500 ? 
      "<span class='alert alert-danger>" : 
      "<span class='alert alert-success>") + data.info + "</span>");
    

    Grouping 运算符是您在此处使用的,因为它具有最高优先级。

    MDN ON OPERATOR PRECEDENCE

    【讨论】:

    • 可能是因为它仍然构建损坏的 HTML!
    • 它构建破碎的 html
    • @Exinferis 现在没有
    【解决方案3】:

    试试这个:

    $('#hire_button').html(data.code == 500 ?  "<span class='alert alert-danger>" : ("<span class='alert alert-success>" + data.info + "</span>"));
    

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2018-12-28
      • 2011-08-30
      • 1970-01-01
      • 2013-07-12
      相关资源
      最近更新 更多