CSS没有应用于使用jquery在表上新添加的行

时间:2014-08-03 10:49:06

标签: javascript jquery html css

我有一张表,用户可以在其中选择一行。我做了一些CSS来突出显示所选行。用户可以向原始表添加行。问题是选中时不会突出显示添加的行。

HTML PART:

<table class="table_to_fill" id="table_id">
        <thead>
                <tr>
                    <th> title 1 </th>
                    <th> title 2 </th>
                </tr>
        </thead>
        <tbody>

            <tr>
                   <td>old row 1</td>
                   <td>old row 1</td>
            </tr>
            <tr>
                   <td>old row 2</td>
                   <td>old row 1</td>
            </tr>

        </tbody>
</table>

CSS:

.table_to_fill tr:hover, .table_to_fill tr.selected {
background-color: #1E90FF;
color : #fff;
font-weight : bold;}

Javascript:

$(".table_to_fill tr").click(function(){
$(this).addClass("selected").siblings().removeClass("selected");
});

//to add rows
$("#add_row_button").click(function(){
$('#table_id tr:last').after('<tr><td>new row</td><td>new row</td></tr>');
});

那么我做错了什么?谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

使用delegated event,因为在 DOM 准备好之后行已添加到 DOM ,因此事件不会在新添加的行上触发:

$(".table_to_fill").on('click','tr',function(){
$(this).addClass("selected").siblings().removeClass("selected");
});

FIDDLE EXAMPLE

您可以从here

了解jquery活动委派