jquery how can i rewrite this code in a more optimized way
What is the best way to optimize the following so i have a shorter code.
$('#font').live('click', function(){
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseInt(z)+1));
$('#fontTypeBox').show();
});
$('#fontSize').live('click', function(){
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseInt(z)+1));
$('#fontSizeBox').show();
});
$('#fontHeader').live('click', function(){
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseIn开发者_开发百科t(z)+1));
$('#fontHeaderBox').show();
});
If you can change the font
ID to fontType
, do this:
$('#font,#fontSize,#fontHeader').live('click', function(){
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseInt(z)+1));
$('#' + this.id + 'Box').show();
});
Same code, except that it uses the multiple-selector
(docs) to select all three at the same time.
If you can't change that ID, then do this:
$('#font,#fontSize,#fontHeader').live('click', function(){
var theID = this.id === "font" ? "fontType" : this.id;
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseInt(z)+1));
$('#' + theID + 'Box').show();
});
Either abstract this portion of code out to a separate function,
var foo = function() {
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseInt(z)+1));
$('#fontHeaderBox').show();
};
or create a jQuery array of these objects as follows:-
$('#font, #fontSize, #fontHeader').live('click', function(){
var z = $(elmid).css('z-index');
$('#editorWrapperOuter').css('z-index',(parseInt(z)+1));
$('#fontHeaderBox').show();
});
Hopefully the syntax is right.
精彩评论