I have written the code below and I am trying to work out if there is a more efficient way of doing it: i.e. less lines of code and quicker etc.
I am also wondering whether it is OK to declare variables inside of an if
... else if
statement.
function test() {
var x = 3;
if (x > 5) {
var msg = "m", state = "d";
} else if (x < 5) {
var msg = "a", state = "d";
} else {
var msg = "e", state = "n";
}
$('#id1').removeClass().addClass(state);
$('#id2').html("Some text " + msg + " and more text.");
$('#id3').attr('title', "Different text " + msg + " still different text.");
}
As background, the following code is the original code I had before refactoring/rewriting:
function test() { var x = 3; if (x > 5) { $('#id1').removeClass().addClass('d'); $('#id2').html("Some text message and more text."); $('#id3').attr('title', "Different text message still different text."); } else if (x < 5) { $('#id1').removeClass().addClass('d'); $('#id2').html("Some text message2 and more text."); $('#id3').attr('title', "Different text message2 still different text."); } else { $('#id1').removeClass().addClass('n'); $('#id2').html("Some text message3 and more text."); $('#id3').attr('title', "Different text message3 still different text."); } }
x
is always3
... because the code makes no sense.... it's example code ;-) – rolfl♦ Jul 3 at 18:39