gpt4 book ai didi

javascript - 悬停对动态添加的表格行的影响

转载 作者:行者123 更新时间:2023-11-29 19:18:24 25 4
gpt4 key购买 nike

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

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>

我错过了什么?

我这里有一个 fiddle : 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');

关于javascript - 悬停对动态添加的表格行的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34152249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com