2010-04-30 7 views
3

J'essaie d'apprendre jQuery en implémentant un menu simple. J'ai <div> éléments qui agissent comme des boutons et ont des liens en eux. J'essaie d'ajouter des événements onclick aux divs qui naviguent dans le navigateur vers l'adresse du lien dans la div. C'est fondamentalement mon pseudo-code. Quel serait le vrai code? Comment puis-je améliorer cela? Tout commentaire apprécié!jQuery: Menu simple

// Iterate over each menu button 

$('.masterHeaderMenuButton').each(function() { 

    // Get the link in each button and set the button's onclick to 
    // redirect to the link's address 

    var url = $('a', this).attr('href'); 

    this.click(function() { 
     window.location.href = url; 
    }); 

    // If the user is on the page for the current button, hilight it 

    if (window.location.href === url) { 
     $('a', this).addClass("masterHeaderMenuButtonSelected"); 
    } 
}); 

Répondre

1

Essayez cet exemple non testé:

$('.masterHeaderMenuButton a').each(function() { 

    // Get the link in each button and set the button's onclick to 
    // redirect to the link's address 

    var _this = this; // save this ref for click handler. 
    $(this).parent().click(function() { 
     window.location.href = $(_this).attr('href'); 
    }); 

    // If the user is on the page for the current button, highlight it 

    if (window.location.href === url) { 
     $(this).addClass("masterHeaderMenuButtonSelected"); 
    } 
}); 
+0

Vous liez "clic" sur le lien mais je pense que l'OP signifiait le lier à l'ensemble du bouton. –

1

Je ne l'utilise pas vraiment jQuery pour une telle tâche simpliste, surtout si elle implique la redirection de la page. Donc, sauf si vous cherchez à faire un chargement de page de style AJAX, respectez le code HTML standard.

Pour que tâche, j'utiliser ce combo doux:

$('#nav_links li').live('click', function() { 
    var ajax_link = $(this).attr('rel');          

    loadLink(ajax_link); 
}); 

function loadLink(link){ 
    $('#content_window').css('position','relative');        
    $('#content_window').animate({ 
     'left': '20px', 
     'opacity': '0' 
    }, 500, "swing", function() { 

     $.ajax({ 
       url: '../sections/' + link, 
       dataType: 'html', 
       success: function(html) { 
        $('#content_window').html(html); 
       } 
     }); 
    }); 
} 

Impressionnant, non?

Voici le code HTML:

<ul id="nav_links"> 
    <li rel="setting-up.html"><span class="green">|</span>setting up<br></li> 
    <li rel="features.html"><span class="purple">|</span>features<br></li> 
    <li rel="more-uses.html"><span class="blue">|</span>more uses<br></li> 
    <li rel="troubleshooting.html"><span class="yellow">|</span>troubleshooting</li> 
</ul> 

Ayez un plaisir.