繁体   English   中英

将鼠标悬停在动态添加的表行上

[英]Hover effect on dynamically added table row

我在表单元格上有一个带有悬停事件的表,该事件在标题单元格中切换了一个CSS类。 如果我在表中动态添加一行,则该事件不会委托给新添加的行。 我读到如果我使用.on() jquery方法,那么它应该委托给动态添加的内容。 但事实并非如此。

 var table = $("table tr"); var cells = $("tr"); var headerCells = $(".col"); cells.on({ mouseenter: function () { var cellIndex = $(this).index(); headerCells.eq(cellIndex).addClass("column-hover"); }, mouseleave: function () { var cellIndex = $(this).index(); headerCells.eq(cellIndex).removeClass("column-hover"); } }, '.data'); var html = '<tr><td class="item">added row</td><td class="item">added row</td><td class="item">added row</td><td class="item">added row</td><td class="item">added row</td></tr>'; $(".add").click(function() { cells.last().after(html); }); 
 table { border-collapse: collapse; } td { border: 1px solid black; } .column-hover { color: white; background: #2196F3; z-index: 201; font-weight: 500; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class="add">add item</button> <table> <thead> <tr> <th class="col">header 1</th> <th class="col">header 2</th> <th class="col">header 3</th> <th class="col">header 4</th> <th class="col">header 5</th> </tr> </thead> <tbody> <tr> <td class="data">row 1, cell 1</td> <td class="data">row 1, cell 2</td> <td class="data">row 1, cell 3</td> <td class="data">row 1, cell 4</td> <td class="data">row 1, cell 5</td> </tr> <tr> <td class="data">row 2, cell 1</td> <td class="data">row 2, cell 2</td> <td class="data">row 2, cell 3</td> <td class="data">row 2, cell 4</td> <td class="data">row 2, cell 5</td> </tr> <tr> <td class="data">row 3, cell 1</td> <td class="data">row 3, cell 2</td> <td class="data">row 3, cell 3</td> <td class="data">row 3, cell 4</td> <td class="data">row 3, cell 5</td> </tr> <tr> <td class="data">row 4, cell 1</td> <td class="data">row 4, cell 2</td> <td class="data">row 4, cell 3</td> <td class="data">row 4, cell 4</td> <td class="data">row 4, cell 5</td> </tr> <tr> <td class="data">row 5, cell 1</td> <td class="data">row 5, cell 2</td> <td class="data">row 5, cell 3</td> <td class="data">row 5, cell 4</td> <td class="data">row 5, cell 5</td> </tr> </tbody> </table> 

我想念什么?

我在这里有一个小提琴: http : //jsfiddle.net/Ltcppvpy/

附加的html (变量html )没有类.data因此首先应将其添加到事件选择器列表( '.data, .item' )中,并且在向其添加元素时不更新cells ,因此我的建议是使用$('body')而不是cellscells.on > $('body').on )。

使用以下代码: Jsfiddle

$('body').on({
    mouseenter: function () {
        var cellIndex = $(this).index();
        headerCells.eq(cellIndex).addClass("column-hover");
    },
    mouseleave: function () {
        var cellIndex = $(this).index();
        headerCells.eq(cellIndex).removeClass("column-hover");
    }
}, '.data, .item');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM