我必须创建一个表单,提示用户输入他们的邮政编码、州和街道地址。但首先,用户应该能够在 a 中选择他们的语言<select>
,并且标签和选择选项(例如他们的标题)必须以他们选择的语言设置。
在语言之后,他们应该能够在一个简短的列表中选择他们的国家,并且邮政编码的正则表达式验证当然必须与所选国家匹配。
我想在没有插件的情况下做到这一点。最干净的方法是什么?
到目前为止我想到的:
//Get the selected language and country
function which(){
lang = $('#language').prop('selectedIndex');
country = $('#country').prop('selectedIndex');
if(lang == 1){
pickedLang = "en";
}else if(lang == 2){
pickedLang = "de";
}else if(lang == 3){
pickedLang = "fr";
}
if(country == 1){
pickedCountry = "US";
}else if(country == 2){
pickedCountry = "UK";
}else if(country == 3){
pickedCountry = "DE";
}else if(country == 4){
pickedCountry = "FR";
}else{
pickedCountry = 0;
}
}
然后,更改标签和选项以匹配所选语言:
$('#language').change(function(){
if(pickedLang == "en"){
$('.country label').text('Country');
$('.language label').text('Language');
$('#country option').eq(0).text('Pick a country');
$('#country option').eq(1).text('United States');
$('#country option').eq(2).text('United Kingdom');
$('#country option').eq(3).text('Germany');
$('#country option').eq(4).text('France');
$('.gender label').text('Title');
$('#gender option').eq(0).text('Choose...');
$('#gender option').eq(1).text('Mr.');
$('#gender option').eq(2).text('Ms.');
$('#gender option').eq(3).text('Miss');
$('.name label').text('Name:');
$('.first-name label').text('First name:');
$('.street label').text('Street:');
$('.number label').text('Number:');
if(pickedCountry == "UK"){
$('.postcode label').text('Post Code:');
}else{
$('.postcode label').text('Zip Code:');
}
$('.state label').text('State:');
$('.city label').text('City:');
}else if [...]
但我真的觉得这可以以某种方式简化和清洁。
编辑:感谢 Nicklas,我现在清理了代码并决定使用 JSON 来存储不同语言的所有标签。
{
"en": [
{
"languageLabel": "Language",
"countryLabel": "Country",
"nameLabel": "Name",
"emailLabel": "E-mail",
"streetLabel": "Street",
"nbrLabel": "N°",
"zipLabel": "Zip",
"stateLabel": "State",
"cityLabel": "City",
"sendLabel": "Send"
}
],
"fr": [
{
"languageLabel": "Langue",
"countryLabel": "Pays",
"nameLabel": "Nom",
"emailLabel": "Adresse e-mail",
"streetLabel": "Rue",
"nbrLabel": "N°",
"zipLabel": "CP",
"stateLabel": "Province",
"cityLabel": "Ville",
"sendLabel": "Envoyer"
}
],
"de": [
{
"languageLabel": "Sprache",
"countryLabel": "Land",
"nameLabel": "Name",
"emailLabel": "E-Mail-Adresse",
"streetLabel": "Straße",
"nbrLabel": "N°",
"zipLabel": "PLZ",
"stateLabel": "Staat",
"cityLabel": "Stadt",
"sendLabel": "Senden"
}
]
}
jQuery:
var labels;
$.getJSON("path-to-json-file",function(data){
labels=data;
});
////////// DETECT CHANGES IN THE SELECTBOXES
$('#language, #country').change(function(){
which();
var currentLabels = labels[pickedLanguage];
$('#language-container label').text(currentLabels.languageLabel);
$('#country-container label').text(currentLabels.countryLabel);
});
但是,控制台返回错误并说它无法读取未定义的属性“fr”(或任何其他语言)。由于我根本不熟悉 JSON 的使用,恐怕我在某个地方搞砸了。