javascript - 使用 jQuery 动态添加数据后重新加载 CSS 的最有效方法是什么?

标签 javascript jquery css twitter-bootstrap

此行是在 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>

Live Example | Source

但是这个标记(唯一的变化是 table 标签)将:

<table class="table">
  <tbody>
    <tr id="product1" class = "success">
      <td>1</td>
      <td>product one</td>
    </tr>
  </tbody>
</table>

Live Example | Source

关于javascript - 使用 jQuery 动态添加数据后重新加载 CSS 的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15333003/

相关文章:

javascript - JQuery 验证未在电子邮件字段中实现 'required'

javascript - Cypress - 是否可以在提示中验证文本?

javascript - 溢出隐藏div之外的绝对定位元素

javascript - requestFileSystem 在 Windows XP 上抛出 SECURITY_ERR - Chrome

jquery - 使用动态选项对选择进行动画处理

html - 为什么::first-letter 在我添加 display: flex 或 inline-flex 后立即停止工作?

javascript - meteor :导入目录 - 所需方法的模块化导入

jquery - 为 HTML 表格最后一个单元格中的每个输入元素添加一个日期选择器

javascript - onload javascript将背景图像分配给div

html - 在 Bootstrap 导航栏中居左 <ul> 以适合右边的