10

I'm trying to ensure the Twitter Bootstrap table-stripped CSS 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.

So if I have this HTML with table-stripped included:

<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:

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-stripped style applied.

Even if I add the class manually after creating using this it makes no difference.

$('#table2').addClass('table-hover'); 

I've created a jsFiddle sample so you can see this running.

4

2 回答 2

11

You should use append to tbody instead of before. The way it is now, the rows are added outside of 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.

于 2013-07-16T08:11:15.003 回答
4

Change to .append() to the <tbody> and also fix your missing closing </tr>.

Demo

$('#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.

于 2013-07-16T08:12:18.867 回答