2009-02-10 32 views
1

下面的代碼工作,但我敢肯定有一個更緊湊的方式來達到同樣的效果,特別是字符串替換:有沒有更好的方式來寫這個JavaScript的正則表達式/替換?

$('#nav-main .nav-sub').each(function() { 

    var name = $(this).attr('id'); 

    $(this).children('li').children('a').each(function() { 

     var text = $(this).text().toLowerCase(); 
     var spaces =//g; 
     var sub = /sub-/; 
     var id = name + '-' + text.replace(spaces, '-');  
     var id = id.replace(sub, '');  
     $(this).attr('id', id); 

    }); 

}); 

回答

1
$('#nav-main .nav-sub').each(function() { 
    var name = $(this).attr('id'); 
    $('li a', this).each(function() {  
     this.id = (name + '-' + $(this).text().toLowerCase().replace(/\s/g, '-')).replace(/sub-/, ''); 
    }); 
}); 
相關問題