I try do this:
$('#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?
+
has a greater operator precedence over ternary operators. Group 'em to be clear.
$('#hire_button').html((data.code == 500 ?
"<span class='alert alert-danger>" :
"<span class='alert alert-success>") + data.info + "</span>");
Grouping operator is what you're using here as it has the highest precedence.
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.
尝试这个:
$('#hire_button').html(data.code == 500 ? "<span class='alert alert-danger>" : ("<span class='alert alert-success>" + data.info + "</span>"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.