我在表单元格上有一个带有悬停事件的表,该事件在标题单元格中切换了一个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')
而不是cells
(cells.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');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句