javascript - 使用下拉菜单显示 2 个不同的数据表

标签 javascript php jquery wordpress datatable

我已经在 WordPress 网站上解决了一个问题,但我陷入了困境。我有两个工作数据表(当前都显示在页面上)和一个下拉选择框。我需要下拉框,其中包含 2 个选项(每个表一个)来选择一个表并仅显示该表。

理想情况下,我希望页面加载默认表(id =“mytable”),然后下拉列表可以控制那里的所有内容。

这里是代码,除了表格本身:

<select name='tables' id='select-tables'>
  <option value="mytable">Survey Test Table</option>
  <option value="mytableSurvey">Survey Only</option>
</select>

//This is the code for the dropdown 

<script type="text/javascript"   src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
<script>
(function($) {
$('#select-tables').on('change', function(){
   var table = $(this).find('option:selected');
   $('#' + table).show();
   $('table').not('#' + table).hide();
});
}(jQuery));

两个表都有自己的数据表脚本:

//datatable 1, table id is mytable

<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$('#mytable').DataTable();
   $('.dataTable').wrap('<div class="dataTables_scroll" />');
});
}(jQuery));
</script>

// table 2, table id is mytableSurvey
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$('#mytableSurvey').DataTable();
   $('.dataTable').wrap('<div class="dataTables_scroll" />');
});
}(jQuery));
</script>

由于这是在 WordPress 中,我必须修改下拉代码的 JS 以匹配数据表代码,以便它可以在 WP 中工作。有没有更好的方法为现有数据表使用 JS 编写下拉列表?

最佳答案

你的代码中有很多冗余代码,所以我也会为你减少很多重复。

<select name='tables' id='select-tables'>
  <option value="mytable">Survey Test Table</option>
  <option value="mytableSurvey">Survey Only</option>
</select>

//This is the code for the dropdown 

<script type="text/javascript"   src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
<script type="text/javascript">
(function($) {
$('#select-tables').on('change', function(){
   var table = $(this).find('option:selected');
   $('#' + table).show();
   $('table').not('#' + table).hide();
});
}(jQuery));

(function($) {
$(document).ready(function(){
   $('#mytable').DataTable();
   $('#mytableSurvey').DataTable();
   $('.dataTable').wrap('<div class="dataTables_scroll" />');

   //open the #mytable table on page load and close 'mytableSurvey'
   $('#mytable').show();
   $('#mytableSurvey').hide();
});
}(jQuery));
</script>

关于javascript - 使用下拉菜单显示 2 个不同的数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44116339/

相关文章:

php - 从 Symfony 中的存储库内部记录

javascript - Bootstrap 警报显示一次后不会隐藏

javascript - 如何使用 RequireJS 分解大型 Javascript 文件

php - 将 'max number of client reached' redis 错误消息更改为 ''

javascript - 将元素从一个监听器传递到嵌套监听器

javascript - 试图弄清楚如何在 Chrome 中解决 IE 的 document.frames ["someframe"].function

javascript - 如何设置动画图标在一段时间后停止

javascript - 选择 GridView 中的所有复选框

c# - 从 C# 程序集中执行 JavaScript

php - SQL如何从多行的逗号分隔列表中删除一个数字