使用jQuery-toggles的数据表不能在第1页以外的页面上工作

我有一个数据表,正在填充服务器端代码。

 @foreach (var item in Model.crmContactsList) {  } 
Name Position
@item.fname @if (item.claimsOpenedAlert) {
} else {
}

我使用这个jQuery来初始化所有要设置为数据库返回的jQuery Toggles。

 jQuery('.toggle').each(function () { $(this).toggles({ on: $(this).data('toggle-on') }); }); 

我使用此代码在单击时更改其状态。 关闭继续,反之亦然。

 // Toggle Switches $('.toggle').on('click', function () { console.log($(this).data('toggle-on')); if ($(this).data('toggle-on') == true) { $(this).data('toggle-on', false) console.log('Turning off ' + $(this).data('contact-id')); } else { $(this).data('toggle-on', true) console.log('Turning on ' + $(this).data('contact-id')); } }); 

现在所有这一切都完美无缺,除非我点击数据表的第一页以外的任何页面。 他们都默认开启。

知道为什么这适用于第一页但不适用于数据表中的其他页面?

动态初始化toggles插件,因此您还可以“切换”更改页面,排序等时注入的元素:

 jQuery('#example').on('draw.dt', function() { jQuery('.toggle').each(function() { $(this).toggles({ on: $(this).data('toggle-on') }); }); }); 

您还必须使用委派的事件处理程序。 就像现在一样,您只有第一页上切换的点击处理程序:

 $('#example').on('click', '.toggle', function () { console.log($(this).data('toggle-on')); if ($(this).data('toggle-on') == true) { $(this).data('toggle-on', false) console.log('Turning off ' + $(this).data('contact-id')); } else { $(this).data('toggle-on', true) console.log('Turning on ' + $(this).data('contact-id')); } }); 

demo – > http://jsfiddle.net/gmptpbqg/其中所有.toggle元素都变为“toggled”,并且在页面中正确记住开/关状态。

你可以像这样使用DataTable回调函数:

 $('#email_alerts').DataTable( { "scrollCollapse": true, "paging": true, "fnDrawCallback": function() { jQuery('.toggle').bootstrapToggle(); } } ); 

这对我来说可以。 祝好运!!!