此行是在 ajax 调用之后添加的:
<tr id="product1" class = "success">
<td>1</td>
<td>product one</td>
</tr>
success
类为该行设置了绿色背景,但显然这种样式已丢失,因为该行是动态添加的。
我见过通过动态加载 CSS 来解决的解决方案,但我想知道如果您拥有大量样式表,哪种方法最有效。 谢谢
我正在使用助推器:
<table id = "table_result" class="table">
<thead id ="table_result_search">
<tr>
<th>#</th>
<th>Product</th>
<th>Price</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
和 Jquery:
//ajax
var tr = TrTableResult(id,nombre, stock, price, n);
$("#table_result_search").append(tr);
//fin ajax
function TrTableResult(id,nombre,stock,price,n){
var color = new Array("success", "error", "warning", "info");
var tr = '<tr id ="'+id+'" class="' + color[n] + '">';
tr+= '<td>'+ id +'</td>';
tr+= '<td>'+ product+'</td>';
tr+= '<td>'+ price +'</td>';
tr+= '<td>'+ stock +'</td>';
tr+= '</tr>';
return tr;
}
最佳答案
更新的答案:
现在您已经引用了您的标记和代码,很明显您确实拥有 table
类,所以下面的原始答案不是它。
但请注意,您将 tr
附加到 thead
元素:
$("#table_result_search").append(tr);
你的标记在哪里:
<thead id ="table_result_search">
您没有看到 success
类的任何效果,因为规则是:
.table tbody tr.success > td {
background-color: #dff0d8;
}
注意那里的tbody
。所以选择器不匹配,因为您将行附加到 thead
,而不是 tbody
。
原始答案:
正如我们中的一些人在评论中指出的那样,浏览器会将 CSS 应用于与相关选择器匹配的所有元素,无论是否动态添加。
如果问题是 success
类似乎没有工作,可能是因为您的 table< 中缺少
元素(是的,真的)。table
类
bootstrap 的 CSS 规则是:
.table tbody tr.success > td {
background-color: #dff0d8;
}
请注意,它以类选择器(.table
)开头,而不是标签选择器(table
)。
例如,此标记将不会将这些样式应用到此表中的td
:
<table>
<tbody>
<tr id="product1" class = "success">
<td>1</td>
<td>product one</td>
</tr>
</tbody>
</table>
但是这个标记(唯一的变化是 table
标签)将:
<table class="table">
<tbody>
<tr id="product1" class = "success">
<td>1</td>
<td>product one</td>
</tr>
</tbody>
</table>
关于javascript - 使用 jQuery 动态添加数据后重新加载 CSS 的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15333003/