I have below code written in jQuery:
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');
}
The code above have repetitive task, Can we make the code compact? I want to minimize this code. How should I achieve this?
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]);
}
}
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');
精彩评论