I have created the following if else statement but there are so many if else statement. I want to learn how can I make it shorthand?
if(REL == 'Like'){
$('#Like' + dataid).attr('rel', 'NotLike');
} else if(REL == 'Love') {
$('#Love' + dataid).attr('rel', 'NotLove');
} else if(REL == 'Unbelievable'){
$('#Unbelievable' + dataid).attr('rel', 'NotUnbelievable');
} else if(REL == 'Spectacular'){
$('#Spectacular' + dataid).attr('rel', 'NotSpectacular');
} else if(REL == 'Emotional'){
$('#Emotional' + dataid).attr('rel', 'NotEmotional');
}
Just take the variable with a check.
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(REL) !== -1) {
$('#' + REL + dataid).attr('rel', 'Not' + REL);
}
For a flip-flop based on strings starting with 'Not'
, you may use this
var temp = REL,
not = 'Not';
if (REL.substring(0, 3) === 'Not') {
temp = REL.substring(3);
not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
$('#' + REL + dataid).attr('rel', not + temp);
}
Proposal with state saver
var lastState = '';
function change(state) {
var temp = state,
not = 'Not';
if (state.substring(0, 3) === 'Not') {
temp = state.substring(3);
not = '';
}
if (['Like', 'Love', 'Unbelievable', 'Spectacular', 'Emotional'].indexOf(temp) !== -1) {
$('#' + temp + dataid).attr('rel', not + temp);
}
return not + temp;
}
// usage always both together:
change(lastState); // to reset the last state
lastState = change(REL); // call change and save the actual state
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With