jQuery replacement for switch
Good Day.
I'm looking for switch
replacement in jQuery. Basically, I have no idea how to replace switch
.
I got following switch
, for about 70 countries. Is there any way to replace it with a loop
?
$("#country").change(function () {
switch ($('#country :selected').val()) {
case 'pl':
$("fieldset#state").hide().load('pl.txt').fadeIn(800);
break;
}
});
Also, is there any possibility to implement loading specific file automatically if there's already selected item?
Edit:
My description of the problem was not the best. Sorry for that. The main problem is:
- I have lists only for some countries, not for all of them
- I was using
switch
for country to read file, if there was no, I was inserting text field by default - I also need to implement loading file by default. What do I mean? I query databas开发者_如何学运维e for country and then I'm selecting it on country drop down list. How to load file automatically (if any)?
Regards, Tom
You can do like this:
$("#country").change(function () {
$("fieldset#state").hide().load($('#country :selected').val() + '.txt').fadeIn(800);
});
Edit:
For the list of available country, you can put them in an array, then do the search
$("#country").change(function () {
var supportCountries = ['pl',]; //put more here
var country = $('#country :selected').val();
if(supportCountries.indexOf(country))
$("fieldset#state").hide().load(country + '.txt').fadeIn(800);
else
$("fieldset#state").hide().load('default.txt').fadeIn(800); //here is load the default text, change if you has another way.
});
For more detail, if you want to replace switch
, then let's use for
/loop
to find the matching case, then execute the action for that case.
How about this, it assumes you follow the convention of using the country code "pl" in the name of the text file "pl.txt" ...
$("#country").change(function () {
var fileName = $('#country :selected').val() + '.txt';
$("fieldset#state").hide().load(fileName).fadeIn(800);
});
If the text files always have the same name as the value in your form element, then you could just make a variable like so
$("#country").change(function () {
var counrty = $('#country :selected').val();
$("fieldset#state").hide().load(country+ '.txt').fadeIn(800);
}
});
Can you make an associative array (ie, object) keyed with of all $('#country :selected').val()
values and mapped to 1) functions, or 2) objects with fields suitable for the operation you want to perform for each?
Then you could do
var lookup = { 'p1': function() { $("fieldset#state").hide().load('pl.txt').fadeIn(800); } }
//or
var lookup = { 'p1': { selector: 'p1.txt', speed: 800 } };
action = lookup[$('#country :selected').val()];
action();
//or
$("fieldset#state").hide().load(action.selector).fadeIn(action.speed)
精彩评论