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

如果其中一个变量值为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>‘之后它会插入包含数据的表格.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...