如何动态启用/禁用响应扩展 [英] How to dynamically enable/disable Responsive extension
问题描述
我有一个项目,用户需要选择附带的脚本是否激活jQuery DataTables的自适应扩展.
I have a project where users need to be able to select whether or not the accompanying script activates Responsive extension of jQuery DataTables.
我想在HTML中添加一个下拉菜单,允许用户选择在dataTable()
初始化选项中将选项responsive
设置为true
还是false
.
I want to add a dropdown menu in HTML that lets users choose whether option responsive
is set to true
or false
in dataTable()
initialization options.
我试图添加一个单独的函数来选择值,并使用一个全局变量将其获取到dataTable()
函数中,但无法使其正常工作.
I tried to add a separate function to select the value and used a global variable to get it to the dataTable()
function but couldn't get that to work.
JavaScript:
$(document).ready(function(){
$("#example").dataTable({
"responsive": false,
"processing": false,
"serverSide": true,
"ajax": "scripts/university.php",
"columns": [
// ID
null, ........
* HTML **
*HTML**
<select id="selected2" onchange="myFunction()">
<option value="true">true</option>
<option value="false">false</option>
</select>
我尝试将document.getElementById
子句添加为dataTable函数的第一行,但无法使其正常工作.
I tried adding a document.getElementById
clause as the first line in the dataTable function but couldn't make it work.
我可以在现有功能中添加什么以使用户可以从HTML页面上的列表中选择responsive
选项?
What can I add to the existing function to make responsive
option user selectable from the list on the HTML page?
推荐答案
解决方案
您需要销毁表以重新初始化它并启用/禁用响应式扩展. >
You need to destroy table to re-initialize it and enable/disable Responsive extension.
var dtOptions = {
responsive: true
};
var table = $('#example').DataTable(dtOptions);
$('#ctrl-select').on('change', function(){
dtOptions.responsive = ($(this).val() === "1") ? true : false;
$('#example').DataTable().destroy();
$('#example').removeClass('dtr-inline collapsed');
table = $('#example').DataTable(dtOptions);
});
注释
当表被销毁时,响应式扩展会留下一些类(dtr-inline
,collapsed
),因此在再次初始化表之前,我会手动删除它们.
When the table is destroyed, Responsive extension leaves some classes (dtr-inline
, collapsed
), so I remove them manually before initializing the table again.
此外,我建议将所有选项都放在单独的对象dtOptions
中,以使重新初始化更加容易,那样,您只需要切换一个选项responsive
.
Also I suggest having all options in a separate object dtOptions
to make re-initialization easier, that way you just need to toggle one option responsive
.
演示
有关代码和演示,请参见此jsFiddle .
See this jsFiddle for code and demonstration.
这篇关于如何动态启用/禁用响应扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!