级联下拉列表,将<选项>值作为 ID 传递
Cascading dropdown, pass <option> value as ID
我一直在使用此处找到的解决方案构建一个基于 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' }
]}
];
相关文章:
- 将参数中类似形式的ID传递给函数click()
- jQuery值在html中作为id传递
- 将外部函数返回的id传递给内部函数
- 如何将特定 ID 传递给嵌入式 YouTube 播放器
- 如何将WordPress帖子ID传递到HTML5本地存储
- 将动态ID传递到成功主干上的url
- 将输入id传递到jquery ui自动完成中的url
- Js:将按钮 ID 传递到同一页面
- 将ID传递给单击事件
- 如何使用 Codeigniter 将 id 传递给引导模式
- ID 传递到函数中的问题
- ID传递网站的替代项
- 级联下拉列表,将<选项>值作为 ID 传递
- 将当前路由活动 ID 传递给组件
- 如何将 id 传递给函数
- 将 Ajax.Actionlink OnSuccess 上的模型 id 传递给另一个 Javascript 函数
- 使用 JavaScript 将选定的复选框 ID 传递到弹出窗口
- 在行单击时,将记录 ID 传递给引导模式中的链接按钮
- 如何将项目id传递给我的控制器以进行删除方法
- 将表单id传递给函数并在函数内提交