Bootstrap Table使用rowStyle设置行背景色无效问题求助
问题分析与修复方案
你的代码里有两个关键问题导致行样式没有生效,我来逐一拆解并修复:
1. 引用了不存在的字段 row.trx_type
你在rowStyle函数里判断row.trx_type是否包含"Purchase"或"Sale",但从你调用的API返回的todos数据里,根本没有trx_type这个字段。你的BuySellFormatter只是把completed字段的显示内容改成了Purchase/Sale,但并没有修改原始的row数据结构,所以row.trx_type始终是undefined,判断条件永远不成立,样式自然不会应用。
解决方法是:在rowStyle里复用BuySellFormatter的判断逻辑,直接检查row.title是否包含"et",来区分Purchase和Sale类型。
2. JavaScript对象语法错误
在rowStyle的返回值里,你写了:
return { css: { 'background-color': 'lightcoral'; } }
这里的lightcoral后面多了一个分号,这不符合JavaScript对象的语法规范,应该把分号去掉(如果有多个CSS属性的话用逗号分隔,单个属性直接结束即可)。
修正后的完整代码
JavaScript部分
function ajaxRequest(params) { var url = 'https://jsonplaceholder.typicode.com/todos' $.get(url + '?' + $.param(params.data)).then(function(res) { params.success(res) console.log(res) }) } function rowStyle(row, index) { // 复用BuySellFormatter的判断逻辑,直接检查title字段 if (row.title.includes("et")) { // 修正对象语法,去掉多余分号 return { css: { 'background-color': 'lightcoral' } } } else { return { css: { 'background-color': 'lightgreen' } } } } function BuySellFormatter(value, row, index) { if (row.title.includes("et")) { return "Purchase" } return "Sale" }
HTML部分(无需修改)
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <link href="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script> <script src="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.js"></script> <h2>Products</h2> <table id="table_2" data-toggle="table" data-height="1200" data-page-size="50" data-ajax="ajaxRequest" data-pagination="true" data-row-style="rowStyle" class="table table-striped table-hover"> <thead> <tr> <th data-field="userId" scope="col">userId</th> <th data-field="id" scope="col">id</th> <th data-field="title" scope="col">title</th> <th data-field="completed" scope="col" data-formatter="BuySellFormatter">Buy/Sell</th> <th data-field="completed" scope="col">completed</th> </tr> </thead> </table>
额外优化建议
如果后续你的数据结构里真的会有trx_type字段,或者你想让代码逻辑更清晰,可以在BuySellFormatter里把格式化后的类型存到row的自定义属性里:
function BuySellFormatter(value, row, index) { let type = row.title.includes("et") ? "Purchase" : "Sale"; // 把类型存到row的自定义属性中 row.trx_type = type; return type; }
这样rowStyle里就可以直接用row.trx_type来判断了:
function rowStyle(row, index) { if (row.trx_type === "Purchase") { return { css: { 'background-color': 'lightcoral' } } } if (row.trx_type === "Sale") { return { css: { 'background-color': 'lightgreen' } } } }
内容的提问来源于stack exchange,提问作者Carol.Kar
相关产品推荐
相关产品推荐

