views:

47

answers:

2

Hello I have:

 var href    = window.location.href; 
if(href.search('/welcome\\/') >  0) 
            { 
                $('.menuwelcome').css('display', 'block'); 
                $('#welcome2').append('<b>Приглашаем субагентов</b>').find('a').remove(); 
                $('#welcome2').find('img').attr('src', '/static/images/arrow_black.gif'); 
            } 
            if(href.search('/contacts\\/') > 0) 
            { 
                $('.menuwelcome').css('display', 'block'); 
                $('#mcontacts').append('<b>Контакты</b>').find('a').remove(); 
                $('#mcontacts').find('img').attr('src', '/static/images/arrow_black_down.gif'); 
            } 
            if(href.search('/sindbad_history\\/') > 0) 
            { 
                $('.menuwelcome').css('display', 'block'); 
                $('.menuwelcome:first').append('<b>История</b>').find('a').remove(); 
                $('.menuwelcome:first').find('img').attr('src', '/static/images/arrow_black.gif'); 
            } 
            if(href.search('/insurance\\/') > 0) 
            { 
                $('.menusafe').css('display', 'block'); 
                $('#msafe').append('<b>Страхование</b>').find('a').remove(); 
                $('#msafe').find('img').attr('src', '/static/images/arrow_black_down.gif'); 
            } 
            if(href.search('/insurance_advices\\/') > 0) 
            { 
                $('.menusafe').css('display', 'block'); 
                $('.menusafe:first').append('<b>Полезная информация</b>').find('a').remove(); 
                $('.menusafe:first').find('img').attr('src', '/static/images/arrow_black.gif'); 
            } 

How can I minimize this code? Sorry for bad english

+3  A: 

Place all the variable bits in a dictionary of arrays:

cases = {
    '/welcome\\/' : ['.menuwelcome', '#welcome2' , 'Приглашаем субагентов', 'arrow_black.gif'     ],
    '/contacts\\/': ['.menuwelcome', '#mcontacts', 'Контакты'             , 'arrow_black_down.gif'],
    ...
};

Then loop over the cases:

for (c in cases) {
    if (href.search(c)) {
        a = cases[c];
        $(a[0]).css('display', 'block'); 
        $(a[1]).append('<b>' + a[2] + '</b>').find('a').remove(); 
        $(a[1]).find('img').attr('src', '/static/images/' + a[3]); 
    } 
}
Marcelo Cantos
Great idea. Note that the image url is different in the various cases as well. Probably want to `break` out of the loop once you've found a match as well.
tvanfosson
Thank you, @tvanfosson. I missed the variation in the images. Amended.
Marcelo Cantos
A: 

If the link that you are removing contains the same text that you are inserting, which I suspect is the case, you could use unwrap instead of keeping track of it. This would make it more resilent to changes in the text. I'd also prefer using a class to change the font style for the "current" menu item. Keying off @Marcelo's solution:

   $(a[1]).find('a').unwrap().addClass('current-menu-item');
tvanfosson