自动加载一个html表格与组合框

Auto-Load a html table with combobox

本文关键字:表格 html 组合 一个 加载      更新时间:2023-09-26

当我在组合框中选择一个选项时,我想加载不同的html表。例如,如果我有一个包含4个类别(汽车,自行车,摩托车和飞机)的组合框,我希望当我选择其中一个选项时,特定的表加载…表的大小可能不同(不是所有的表都是3行3单元格,每个表的结构可能不一样)

 <select name="um" id="um" class="select_opt">
 <option value="Car">Car</option>"
 <option value="Bike">Bike</option>"
 <option value="Motorbike">Motorbike</option>"
 <option value="Airplane">Airplane</option>"
 <table id="Car" cellspacing="0">
   <tr>
  <th scope="alt">Title 1</th>
   </tr>  
   <tr>
     <td>Something 1</td>
     <td>Something 2</td>
   </tr>
 </table>

我有一个组合框和一个表,当我选择"Car"选项时,我想看到那个表…与组合框中的其他选项相同。

我该怎么做?

这里有两种方法可以做到这一点,一种是使用纯JavaScript(没有库),另一种是使用jQuery。

该过程包括隐藏所有表,然后根据所选选项的值选择要显示的正确表。

示例表有不同的列(1-4),因为您提到您的表也可能有不同的大小。

只JavaScript:

例子jsfiddle

var tables = [
    document.getElementById('Car'),
    document.getElementById('Bike'),
    document.getElementById('Motorbike'),
    document.getElementById('Airplane')
];
document.getElementById('um').onchange = function() {
    // hide all tables
    for (var i in tables) {
        tables[i].style.display = "none";
    }
    // get selected value and show it's table
    var selectedValue = this[this.selectedIndex].value;
    if (selectedValue) {
        document.getElementById(selectedValue).style.display = "block";
    }
};
jQuery:

例子jsfiddle

// reuse variable to hide all tables
var $tables = $('table');
// Combobox change event
$('.select_opt').change(function() {
    $tables.hide();
    $('#' + $(this).val()).show();
});