带有jQuery切换的数据表在第1页以外的其他页面上不起作用 [英] Datatables with jQuery-toggles not working on pages other than page 1
问题描述
我有一个用服务器端代码填充的数据表.
I have a Data-table that is being populated with server-side code.
<table id="email_alerts" class="table">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.crmContactsList)
{
<tr>
<td>@item.fname</td>
<td>
@if (item.claimsOpenedAlert)
{
<div class="control-label">
<div class="toggle toggle-primary" data-toggle-on="true" data-contact-id="@item.crmContactID"></div>
</div>
}
else
{
<div class="control-label">
<div class="toggle toggle-primary" data-toggle-on="false" data-contact-id="@item.crmContactID"></div>
</div>
}
</td>
</tr>
}
</tbody>
</table>
我使用此jQuery初始化将所有jQuery Toggles设置为数据库返回的内容.
I use this jQuery to initialize all of the jQuery Toggles to be set to what the database returned.
jQuery('.toggle').each(function () {
$(this).toggles({
on: $(this).data('toggle-on')
});
});
当他们被点击时,我使用这段代码来改变它们的状态.从关到开,反之亦然.
I use this code to alter their state when they are clicked on. Off goes to on and vice versa.
// 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'));
}
});
现在,所有这些都可以完美地工作,除非当我单击除数据表首页以外的任何页面时. Page 2+都默认为打开.
Now all of this works perfectly, except when I click on any page other than the first page for Data-tables. Page 2+ they all default to being turned on.
您知道为什么它适用于数据表的第一页而不适用于其他页吗?
Any idea why this works for the first page but not for other pages in data-tables?
推荐答案
动态初始化toggles插件,因此您还可以切换"在更改页面,排序等时注入的元素:
Initialise the toggles plugin dynamically, so you also "toggles" elements injected when changing page, sorting etc :
jQuery('#example').on('draw.dt', function() {
jQuery('.toggle').each(function() {
$(this).toggles({
on: $(this).data('toggle-on')
});
});
});
还必须使用委托的事件处理程序.现在,您只有首页的切换按钮有一个点击处理程序:
You must also use a delegated event handler. As it is now, you only have a click-handler for the toggles on the first page :
$('#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'));
}
});
演示-> http://jsfiddle.net/gmptpbqg/ 所有.toggle
元素都变为切换",并且在页面之间正确记住了开/关状态.
demo -> http://jsfiddle.net/gmptpbqg/ where all .toggle
elements become "toggled" and on / off state is remembered correctly across the pages.
这篇关于带有jQuery切换的数据表在第1页以外的其他页面上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!