如果其中一个变量值为1,我想将背景颜色设置为灰色,否则行背景颜色将为白色
但事情是当变量值为1时,则添加了行但不添加了内容.如果变量值为0,则所有操作都按预期工作
我试过以下代码:
function insertRow(value){ $('#invoiceTable').append( value === 1 ? '<tr style="background-color: #ccc8cb">' : '<tr>'+ '<td> category </td>' + '<td> material </td>' + '<td> ups </td>' + '</tr>' ); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table id="invoiceTable" class="table table-bordered table-hover" > <thead> <tr> <th>Category</th> <th>Material</th> <th>ups</th> </tr> </thead> <tbody> </tbody> </table> <input type=button value='insert ash row' onclick='insertRow(1)'/> <input type=button value='insert white row' onclick='insertRow(0)'/>
请指出我做错了什么.
解决方法
把()放在值=== 1附近? ‘< tr style =“background-color:ash”>‘ :’< tr>‘解决了这个问题:
(value === 1 ? '<tr style="background-color:ash">' : '<tr>')
您的代码正在执行的操作如下:如果值=== 1则插入’< tr style =“background-color:ash”>‘否则插入此:
'<tr>'+ '<td> category </td>' + '<td> material </td>' + '<td> ups </td>' + '</tr>'
所以在它周围放置括号将确保它使用’< tr style =“background-color:ash”>‘或’< tr>‘之后它会插入包含数据的表格.