表行突出显示不适用于动态行

时间:2015-05-26 15:14:25

标签: javascript jquery html

我尝试使用jquery动态添加行并附加鼠标事件以突出显示该行。它在第一次添加行时有效,但在后续行添加时,上一行的突出显示停止工作。

这是小提琴: JS Fiddle

HTML

<table border=1 id="testTable">
<thead>
    <tr>
        <td>Column 1</td>
        <td>Column 2</td>
        <td>Column 3</td>
    </tr>
</thead>
<tbody>
</tbody>            
</table>
<input type="submit" id="add" value="Add"/>

JS

$(function(){
    $("#add").on('click',function(){
        console.log("Add clicked");
        $('<tr>').append(
            $('<td>').text('Val1'),
            $('<td>').text('Val2'),
            $('<td>').text('Val3')
            ).appendTo('#testTable');
        highlight('testTable');
    });
    function highlight(tableid){
        var row = tableid+" tbody tr";
        $("#"+row).on('mouseover mouseout', (function(){
            $(this).toggleClass("highlight");
        }
                                            ))}                                             

});

CSS

tr.highlight td{background: #B0C4DE}

4 个答案:

答案 0 :(得分:6)

无需明确地向每一行添加事件。

$("#testTable tbody").on('mouseover mouseout', 'tr', function() {
    $(this).toggleClass("highlight");
});

这会将事件添加到所有tr甚至动态附加。

演示:https://jsfiddle.net/tusharj/2pnjshL0/11/

答案 1 :(得分:1)

在附加鼠标事件之前使用.off(),因为您多次绑定事件并导致悬停问题。最好的解决方法是只附加一次事件,这样你就不必每次都解开事件。

$("#"+row).off().on('mouseover mouseout', (function() {
    $(this).toggleClass("highlight");
});

希望有所帮助

http://jsfiddle.net/2pnjshL0/9/

答案 2 :(得分:0)

http://jsfiddle.net/2pnjshL0/10/

$(function() {
    $("#add").on('click', function() {
        console.log("Add clicked");
        $('<tr>').append(
            $('<td>').text('Val1'),
            $('<td>').text('Val2'),
            $('<td>').text('Val3')
        ).appendTo('#testTable');
        highlight('testTable');
    });

    function highlight(tableid) {
        var row = tableid + " tbody";
        $("#" + row).on('mouseover mouseout', 'tr', (function() {
            $(this).toggleClass("highlight");
        }))
    }

});

答案 3 :(得分:0)

更改应用突出显示的功能:

function highlight(tableid){
    $("#testTable tbody :last-child").on('mouseover mouseout', function(){
         $(this).toggleClass("highlight");
    })
}

这只会在添加每一行后将事件应用于tbody中的最后一个子元素。使它比解除所有内容更有效率再次重新绑定它。

相关问题