我在下拉列表的更改功能中访问多个值时遇到问题。
我有 JSON格式之类的;
{
lang: [
{
Code: "ar",
name: "العربية",
direction: "rtl"
},
{
Code: "da",
name: "Danske",
direction: "ltr"
},
{
Code: "du",
name: "Nederlands",
direction: "ltr"
},
{
Code: "en",
name: "English",
direction: ""
},
{
Code: "es",
name: "Español",
direction: "ltr"
},
{
Code: "fi",
name: "Suomeksi",
direction: "ltr"
},
{
Code: "fr",
name: "Français",
direction: "ltr"
},
{
Code: "ge",
name: "Deutsch",
direction: "ltr"
},
{
Code: "it",
name: "Italiano",
direction: "ltr"
},
{
Code: "no",
name: "Norge",
direction: "ltr"
},
{
Code: "pl",
name: "Polski",
direction: "ltr"
},
{
Code: "pt",
name: "Portuguese ",
direction: ""
},
{
Code: "ru",
name: "Русский",
direction: "ltr"
},
{
Code: "se",
name: "Svenska",
direction: "ltr"
}
]
在我的下拉列表/选择框中访问此JSON的代码;
function loadlanguages(){
$.ajax({
url:'https://xxxx/json/lang_list.php?json=1&rcg_mobile=2',
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success: function(data, textStatus, jqXHR){
var count = data.lang.length;
var set_languages=$('#languageselector');
var set_languages_ = '';
set_languages.empty();
for(var i =0;i < count;i++)
{
set_languages_ += '<option value='+data.lang[i].Code+'>'+data.lang[i].name+'</option>';
}
set_languages.append(set_languages_);
},
error: function(XMLHttpRequest, textStatus, errorThrown){hideLoading();alert_unable_to_access();}
});
}
现在一切都已成功加载。但是当我选择任何一种语言时;我希望得到相应的“方向”。
我如何管理这个?当我选择任何一种语言时,我怎么能得到方向? 我认为这是一件简单的事情..但我没有得到这个解决方案.. 请帮忙..!!! :(
答案 0 :(得分:2)
在成功方法内的选项中设置data-*
属性,如:
'<option data-direction="' + data.lang[i].direction + '" value='+data.lang[i].Code+'>'+data.lang[i].name+'</option>'
并且在js代码中你可以像
那样得到它$('#languageselector option:selected').data('direction');
答案 1 :(得分:1)
将该行修改为:
set_languages_ += '<option _direction='+data.lang[i].direction+' value='+data.lang[i].Code+'>'+data.lang[i].name+'</option>';
in for循环。
在js
$('#languageselector').change(function(){
console.log($('#languageselector').attr('_direction'));
});
这将获取下拉菜单的更改/选定值
答案 2 :(得分:1)
将set_languages字符串更改为
set_languages_ += '<option data-direction='+data.lang[i].direction+' value='+data.lang[i].Code+'>'+data.lang[i].name+'</option>';
并且您的更改侦听器将如下所示:
$('#languageselector').on("change",function(e){
// direction contains the appropriate direction
var direction = $(this).attr("data-direction");
})