Bob*_*b76 0 html javascript jquery
我尝试使用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"/>
Run Code Online (Sandbox Code Playgroud)
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");
}
))}
});
Run Code Online (Sandbox Code Playgroud)
CSS
tr.highlight td{background: #B0C4DE}
Run Code Online (Sandbox Code Playgroud)
无需显式向每一行添加事件.
$("#testTable tbody").on('mouseover mouseout', 'tr', function() {
$(this).toggleClass("highlight");
});
Run Code Online (Sandbox Code Playgroud)
这将把事件添加到所有trs甚至动态附加.
演示:https://jsfiddle.net/tusharj/2pnjshL0/11/