Optimize jQuery Function
It's possible to optimize and minify this sample function? How could I do it?
$(function () {
$("#options").change(function () {
var message_index = $("#options").val();
if (message_index == 0) {
$("#display_image").show();
$("#display_flash, #display_youtube, #display_google").hide();
} else if (message_index == 1) {
$("#display_flash").show();
$("#display_image, #display_youtube, #display_google").hide();
} else if (message_index == 2) {
$("#display_youtube").show();
$("#display_image, #display_flash, #display_google").hide();
} else if (message_index == 3) {
$("#display_google").show();
$("#display_image, #display_flash, #display_youtube").hide();
} els开发者_JS百科e {
$("#display_image, #display_flash, #display_youtube, #display_google").hide();
}
});
});
$(function () {
var $displays = $("#display_flash, #display_youtube, #display_google, #display_image"),
toShow = ['image','flash','youtube','google'];
$("#options").change(function () {
$displays.hide();
$("#display_"+toShow[$(this).val()]).show();
});
});
Not really much optimisation, but certainly cleaner IMO:
$(function () {
$("#options").change(function () {
// hide everything
$("#display_image, #display_flash, #display_youtube, #display_google").hide();
switch ($("#options").val()) {
case 0:
$("#display_image").show();
break;
case 1:
$("#display_flash").show();
break;
case 2:
$("#display_youtube").show();
break;
case 3:
$("#display_google").show();
break;
}
});
});
To minify, use http://jscompress.com/
If you want to minify that code, try putting it into here - http://www.minifyjavascript.com/
With your current code, you could do something like this:
$("#options").change(function () {
var message_index = $("#options").val();
var elemIds=[
'#display_image',
'#display_flash',
'#display_youtube',
'#display_google'];
$(elemIds.join(',')).hide();
if (elemIds[message_index]) {
$(elemIds[message_index]).show();
}
});
You haven't provided the markup you're running this on, even further optimizations would be possible based on that. Maybe adding a common class for those showable elements. If the elements are in the right order in the markup (same as the message_index
order), you can go even further with optimizations.
For minification, there are several tools to use, the others have provided you some.
You can get ideas from:
Minify jQuery based js files
How to minify jquery files?
replace your if statement with a switch statement
精彩评论