twitter-bootstrap 动态创建表行后应用 Bootstrap“table-striped”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17671231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Applying Bootstrap "table-striped" after creating table rows dynamically
提问by Bern
I'm trying to ensure the Twitter Bootstraptable-strippedCSS style is applied to a table whose rows are added dynamically at runtime. For some reason, that I'm trying to get to the bottom of, I can't get this particular style to work so that my new rows are styled with the stripped look.
我试图确保Twitter Bootstraptable-strippedCSS 样式应用于在运行时动态添加行的表。出于某种原因,我试图深入了解,我无法让这种特定的样式起作用,因此我的新行采用了剥离外观的样式。
So if I have this HTML with table-strippedincluded:
因此,如果我有table-stripped包含以下内容的 HTML :
<table class="table table-bordered table-striped table-condensed table-hover" id="table2">
<thead>
<tr>
<th>Heading A</th>
<th>Heading B</th>
<th>Heading C</th>
</tr>
</thead>
<tbody></tbody>
</table>
Then I run this JavaScript code:
然后我运行这个 JavaScript 代码:
for (var i = 0; i < 5; i++)
{
$('#table2 > tbody:last').before('<tr><td>' + i +'</td><td>b</td><td>c</td>');
}
I'll get my 5 new rows but they won't have the table-strippedstyle applied.
我会得到我的 5 个新行,但它们不会table-stripped应用样式。
Even if I add the class manually after creating using this it makes no difference.
即使我在使用它创建后手动添加类,它也没有区别。
$('#table2').addClass('table-hover');
I've created a jsFiddle sampleso you can see this running.
我创建了一个jsFiddle 示例,因此您可以看到它正在运行。
回答by Naor Biton
You should use appendto tbodyinstead of before. The way it is now, the rows are added outside of tbody.
您应该使用append到tbody而不是before。现在的方式是,行被添加到tbody之外。
Changing just this line:
只改变这一行:
$('#table2 > tbody:last').append('<tr><td>' + i +'</td><td>b</td><td>c</td>');
Seems to make your jsFiddle work.
似乎让你的 jsFiddle 工作。
回答by MrCode
Change to .append()to the <tbody>and also fix your missing closing </tr>.
更改为.append()到<tbody>并修复丢失的收盘</tr>。
$('#table2 > tbody').append('<tr><td>' + i +'</td><td>b</td><td>c</td></tr>');
By using .before()you were inserting the rows before the tbody which caused the style not to be applied because the Bootstrap style targets rows that are children of the tbody.
通过使用,.before()您在 tbody 之前插入了行,这导致样式无法应用,因为 Bootstrap 样式针对的是 tbody 的子行。

