在 append() 中使用三元表达式

Using a ternary expression inside append()

我试图在 jQuery append() 中使用三元表达式。我检查了控制台,没有显示错误。问题是 tr 没有附加到 tbody

$(".invoice table tbody").append("<tr> \
    <td> <span class=''>" + price.toFixed(0) == 0 ? Obs : 1 + "</span></td> \
    <td> <span class=''>" + price.toFixed(2) + "</span> </td> \
    <td> <input type='checkbox' name='removeItem' class='removeItemCheckBox'/></td> \
</tr>");

? : 运算符不是 "lambda expression";它是 条件运算符 。问题是它的优先级很低所以你必须把它括起来:

$(".invoice table tbody").append("\
        <tr> \
          <td> <span class=''>" + (price.toFixed(0) == 0 ? Obs : 1) + "</span></td> \
          <td> <span class=''>" + price.toFixed(2) + "</span> </td> \
          <td> <input type='checkbox' name='removeItem' class='removeItemCheckBox'/></td> \
        </tr> \
");

如果没有括号,两边的 + 运算符将优先,整个表达式将不同。