三元运算JS不起作用 [英] Ternary operation JS not working
本文介绍了三元运算JS不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试这样做:
$('#hire_button').html(data.code == 500 ? "<span class='alert alert-danger>" : "<span class='alert alert-success>" + data.info + "</span>");
但是它返回或成功>
或为空行.我在做什么错了?
But it returns or success>
or empty row. What I am doing wrong?
推荐答案
?:
三元运算符的优先级低于 +
串联运算符,因此您要构建不匹配的标签.
The ? :
ternary operator has lower precedence that the +
concatenation operator so you're building mis-matched tags.
但是,恕我直言,您应该重构代码以避免重复,并同时自动修复优先级问题:
However, IMHO you should refactor your code to avoid some repetition, and automatically fixing the precedence issue at the same time:
$('#hire_button').empty().append($('<span>', text: data.info, class: 'alert'})
.addClass(data.code == 500 ? 'alert-danger' : 'alert-success'));
注意:以上内容被重写为原始版本,错误地将新类添加到了按钮上,而不是在封闭的范围内添加了新的类.
NB: above rewritten as the original incorrectly added the new class to the button instead of the enclosed span.
这篇关于三元运算JS不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文