【发布时间】:2015-04-27 22:54:18
【问题描述】:
我有一个使用服务器端代码填充的数据表。
<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 以设置为数据库返回的内容。
jQuery('.toggle').each(function () {
$(this).toggles({
on: $(this).data('toggle-on')
});
});
当他们被点击时,我使用这个代码来改变他们的状态。 Off 变为 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'));
}
});
现在所有这些都可以完美运行,除非我单击数据表第一页以外的任何页面。第 2 页以上它们都默认开启。
知道为什么这适用于第一页而不适用于数据表中的其他页面吗?
【问题讨论】:
-
你在哪里调用切换绑定代码?听起来后续页面没有绑定切换事件。您需要在每次绘制表格后调用它,最好是在数据表回调函数中,如
fnRowCallback -
@markpsmith 我认为这是 jQuery 的第一部分。这需要所有 .toggle 类并初始化 Toggle 行为。
标签: jquery jquery-plugins datatables