Javascript 引导数据表tr不';不要一点一点地开枪
请参考此处的示例: 一张桌子是这样的:Javascript 引导数据表tr不';不要一点一点地开枪,javascript,jquery,twitter-bootstrap,Javascript,Jquery,Twitter Bootstrap,请参考此处的示例: 一张桌子是这样的: <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example"> <thead> <tr> <th>Rendering engine</th> <th>Browser</th>
<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类。如果我将onclick='myFunc'添加到所有tr,它就会工作。但我不想用这个。如何使另一种方式起作用?使用事件委派:
它将在动态元素上应用事件
$('#example').on('click', '.reportRow', function () {
alert('mm');
});
参考:
演示:问题在于,您只将单击事件绑定到第一个页面行,而不是第二个页面行,以此类推 在这种情况下,您需要将单击事件委托给表本身。这意味着不必将单独的事件处理程序绑定到每一行,而是绑定某个包装容器上的唯一事件处理程序(如本例中的表;还可以使用
document
或body
)。此容器中发生的单击事件最终将冒泡到您绑定处理程序的容器,您可以在其中处理它
$('#example').on('click', '.reportRow', function(){
alert('mm');
});
演示:还有什么其他方法?你说这两种方法都有效。对不起。编辑消息。
$('#example').on('click', '.reportRow', function(){
alert('mm');
});