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

查看:100
本文介绍了使用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>

例如,如果用户在第一个下拉列表中选择nokia,则第二个下拉列表应该是有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();
    });
});

工作示例可用

Working example is available in jsFiddle.

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

Note that this should work with jQuery mobile just fine.

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

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