我已经在 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/