请参考此处的示例: http://jsfiddle.net/c0kackzw/
表格如下:
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
<thead>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</thead>
<tbody>
<tr class="reportRow odd gradeX">
<td>Trident</td>
<td>Internet
Explorer 4.0</td>
<td>Win 95+</td>
<td class="center"> 4</td>
<td class="center">X</td>
</tr>
单击第一页上的某一行时,单击“函数”可以正常工作,但当您在其他页面上时它不起作用:
$('.reportRow').click(function(){
alert('mm');
});
并且所有行都有reportRow类。如果我将onclick ='myFunc'添加到所有tr s它的工作原理。但我不想用它。我如何使其他方式有效?
答案 0 :(得分:4)
使用事件委托: 它将在动态元素上应用事件。
$('#example').on('click', '.reportRow', function () {
alert('mm');
});
答案 1 :(得分:2)
问题是你只是将点击事件绑定到第一页行,而不是第二页等等。
在这种情况下,您需要将click事件委托给表本身。这意味着不是将单独的事件处理程序绑定到每一行,而是绑定某个包装容器上的唯一一个(如您的情况下的表;您也可以使用document
或body
)。发生在此容器内部的单击事件最终会冒泡到您绑定处理程序的容器,您可以在其中处理它。
$('#example').on('click', '.reportRow', function(){
alert('mm');
});