使用 jquery 动态填充选择选项 [英] Populating select option dynamically with jquery

查看:24
本文介绍了使用 jquery 动态填充选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

会有两个下拉列表,

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

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

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

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

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

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

  <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>

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

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.

推荐答案

新的 javascript 以考虑您更新的 json 结构:

New javascript to take into account your updated json structure:

$(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();
    });
});

工作示例在 jsFiddle 中 在 jsFiddle 中可用.

Working example is available in jsFiddle.

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

Note that this should work with jQuery mobile just fine.

这篇关于使用 jquery 动态填充选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆