Javascript 使用 jquery 动态填充选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8090457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:42:12  来源:igfitidea点击:

Populating select option dynamically with jquery

javascriptjqueryjquery-mobile

提问by Abimaran Kugathasan

There will be two drop down lists,

会有两个下拉列表,

First have the list of mobile vendor, and the second have the list of models per vendor.

第一个是移动供应商列表,第二个是每个供应商的型号列表。

When one select a vendor from the first drop down list, the second drop down list should populate with relevant model for that vendor dynamically. This is for mobile web site, it's better to use jquery-mobile

当从第一个下拉列表中选择供应商时,第二个下拉列表应动态填充该供应商的相关模型。这是针对移动网站的,最好使用jquery-mobile

The option values for the second will in a json map.

第二个选项值将在 json 映射中。

  <select class="mobile-vendor">
    <option value="motorola">Motorola</option>
    <option value="nokia">Nokia</option>
    <option value="android">Android</option>
  </select>

 selectValues = {"nokia"   : {"N97":"download-link", 
                              "N93":"download-link"}, 
                 "motorola": {"M1":"download-link",
                              "M2":"download-link"}}

<select class="model">
    <option></option>
</select>

For example, if the user selects nokia in the first drop down list, the second drop down list should have N97, N93 as the options.

例如,如果用户在第一个下拉列表中选择诺基亚,则第二个下拉列表应该有 N97、N93 作为选项。

回答by GregL

EDIT:New javascript to take into account your updated json structure:

编辑:新的 javascript 考虑到您更新的 json 结构:

$(function() {
    var selectValues = {
        "nokia": {
            "N97": "http://www.google.com",
            "N93": "http://www.stackoverflow.com"
        },
        "motorola": {
            "M1": "http://www.ebay.com",
            "M2": "http://www.twitter.com"
        }
    };

    var $vendor = $('select.mobile-vendor');
    var $model = $('select.model');
    $vendor.change(function() {
        $model.empty().append(function() {
            var output = '';
            $.each(selectValues[$vendor.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });
    }).change();

    // bonus: how to access the download link
    $model.change(function() {
        $('#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
    });
});

Working example is available in jsFiddle.

jsFiddle 中提供工作示例。

Note that this should work with jQuery mobile just fine.

请注意,这应该适用于 jQuery mobile。