级联下拉列表,将<选项>值作为 ID 传递

Cascading dropdown, pass <option> value as ID

本文关键字:ID 传递 选项 下拉列表 级联      更新时间:2023-09-26

我一直在使用此处找到的解决方案构建一个基于 jQuery 的级联下拉列表 链接:Javascript:

jQuery(function($) {
    var locations = {
        'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
        'Spain': ['Barcelona'],
        ...
    }
    var $locations = $('#location');
    $('#country').change(function () {
        var country = $(this).val(), lcns = locations[country] || [];
        var html = $.map(lcns, function(lcn) {
            return '<option value="' + lcn + '">' + lcn + '</option>'
        }).join('');
        $locations.html(html)
    });
});

这很好用,但是我需要传递城市的ID,而不是城市名称本身。我已经想出了如何在值中添加键(在JS方面我不是菜鸟(:

Javascript:

var locations = {
    'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
    'Spain': { 4 : 'Barcelona', 15 : 'Madrid', 21 : 'Marabella'],
    ...
}

问题是:如何将该 id 传递给<option>值...?

Javascript:

return '<option value="' + lcn + '">' + lcn + '</option>'

map() callbak 函数有两个参数用于文本和值。像下面这样更改您的map()

var html = $.map(lcns, function (text, val) {
    return '<option value="' + val + '">' + text + '</option>'
}).join('');

你的对象是错误的。最后]}

'Spain': { 4 : 'Barcelona', 15 : 'Madrid', 21 : 'Marabella'],
//---------------------------------------------------------^----

在数组中使用标准化的对象结构,而不是使用 id 作为对象的键。它更易于阅读,并且数组通常更容易用于重复结构

'Spain': [
    {  id: 4,  city: 'Barcelona' }, 
    {  id: 15, city: 'Madrid' }, 
    {  id: 21, city: 'Marabella' }
]
var html = $.map(lcns, function( item) {
        return '<option value="' + item.id + '">' + item.city + '</option>'
}).join('');

自定义的是按如下方式构建对象:

{ id: 1, city: 'Duesseldorf' }; 

如果你愿意这样做,你可以做这样的事情:

var locations = {
    'Germany': [
    {id: 1, city: 'Duesseldorf'}, {id: 2, city: 'Leinfelden'}]
}; 
var lcns = locations['Germany']; //Just an example 
$.map(lcns, function(lcn) {
    console.log(lcn.id); 
    console.log(lcn.city); 
    return '<option value="' + lcn.id + '">' + lcn.city + '</option>'
}).join(''); 

https://jsfiddle.net/npjdfn0y/2/

我还可以建议将您的对象更改为一系列国家/地区:

[
    { id: 1, country: 'Germany', cities: [
        { id: 1, city: 'Duesseldorf'}, { id: 2, city: 'Leinfelden' }
    ]}, 
    { id: 2, country: 'Spain', cities: [ 
        { id: 11, city: 'Barcelona' }, { id: 12, city: 'Madrid' }
    ]}
];