开发者

jquery how can i rewrite this code in a more optimized way

开发者 https://www.devze.com 2023-02-06 23:43 出处:网络
What is the best way to optimize the following so i have a shorter code. $(\'#font\').live(\'click\', function(){

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消