如何使用内联javascript if语句将样式设置为表行

NuO*_*One 3 html javascript jquery

如果其中一个变量值为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>'
  );
}
Run Code Online (Sandbox Code Playgroud)
<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)'/>
Run Code Online (Sandbox Code Playgroud)

请指出我做错了什么.

Mar*_*ark 5

()围绕value === 1 ? '<tr style="background-color:ash">' : '<tr>'解决问题:

(value === 1 ? '<tr style="background-color:ash">' : '<tr>')
Run Code Online (Sandbox Code Playgroud)

您的代码正在执行的操作如下:如果value === 1插入,'<tr style="background-color:ash">'则插入以下内容:

'<tr>'+
      '<td> category </td>' +
      '<td> material </td>' +
      '<td> ups </td>' +
    '</tr>'
Run Code Online (Sandbox Code Playgroud)

因此,在它周围放置括号将确保它使用'<tr style="background-color:ash">''<tr>'之后它将插入包含您的数据的表.

  • @NuOneTAttygalle因为你当前的代码认为如果value不是1,那么插入所有`'<tr>'+'<td> category </ td>'+'<td> material </ td>'+'<td > ups </ td>'+'</ tr>'`.它将它视为一个大字符串.如果value为1,那么它会插入_only_`'<tr style ="background-color:ash">'`而不是其他内容.其余的被认为是`:`的右手部分.您需要为编译器提供有关哪个部分是可更改部分以及在所有情况下将使用哪个部分的明确说明. (2认同)