Jquery Datatables和Bootstrap Toggle不起作用 [英] Jquery Datatables and Bootstrap Toggle Doesn't work Together
问题描述
我正在使用以下数据资料: https://www.datatables.net/
i'm using datatables from : https://www.datatables.net/
我也使用Bootstrap切换: http://www.bootstraptoggle .com /
and also i'm using Bootstrap Toggle from : http://www.bootstraptoggle.com/
这是我的代码:
<table class="table table-striped table-hover" id="table-list-tour">
<thead>
<tr><th>Featured</th></tr>
</thead>
<tbody>
<?php foreach ($packages as $package) : ?>
<tr>
<td>
<div class="checkbox">
<input type="checkbox" class="shownCheckbox" id="<?php echo $package->id ?>" data-toggle="toggle">
</div>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<Script>
$('#table-list-tour').DataTable();
$(".toggle-group").click(function(){
var selectedCheckBox = $(this);
var id = selectedCheckBox.parent().children('input').attr('id');
var isChecked = selectedCheckBox.is(':checked');
$.ajax({
url : 'A_LINK',
type : 'post',
data : {'id':id},
success:function(data)
{
console.log(data);
if (isChecked && data !== '') {
selectedCheckBox.attr('checked', false);
alert(data);
}
},
error:function()
{
alert('Toggle Failed !');
}
});
});
</script>
问题是,在第1页中,引导切换事件中的AJAX完美运行,当我转到第2页,所有的ajax都没有起作用,
为什么?
The problem is, in page 1, the AJAX in bootstrap toggle event works perfectly, when i move to page 2, all the ajax did not work at all, why ?
推荐答案
原因
在初始化之前DOM不存在第一个以外的页面,这就是为什么处理程序从未被调用。
Pages other than first do not exist in DOM at the time of initialization, that is why your handler never gets called.
解决方案
您需要通过在 on()<)中提供选择器作为第二个参数来使用事件委托/ a>调用,见下面的例子:
You need to use event delegation by providing selector as a second argument in on() call, see example below:
$(document).ready(function(){
$('#table-list-tour').DataTable();
$('#table-list-tour').on('click', '.toggle-group', function(){
// ... skipped ...
});
});
从jQuery on()方法文档:
From jQuery on() method documentation:
委托事件的优点是可以从$ b处理事件$ b后代元素,稍后添加到文档中。
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
请参见jQuery中的直接和委派事件 on()方法文档和 jQuery DataTables - 为什么点击事件处理程序不起作用更多信息。
See "Direct and delegated events" in jQuery on() method documentation and jQuery DataTables – Why click event handler does not work for more information.
这篇关于Jquery Datatables和Bootstrap Toggle不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!