2010-04-30 107 views
3

我想通過實現一個簡單的菜單學習jQuery。我有<div>元素作爲按鈕,並有鏈接。我試圖將onclick事件添加到導航瀏覽器到div中鏈接地址的div。這基本上是我的僞代碼。真實的代碼是什麼?我該如何改進?任何反饋讚賞!jQuery:簡單的菜單

// 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"); 
    } 
}); 

回答

1

試試這個未經測試的例子:

$('.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

您正在綁定「點擊」鏈接,但我認爲OP意味着將其綁定到整個按鈕。 – 2010-05-04 13:52:39

1

我實際上並不使用jQuery這樣一個簡單的任務,特別是當它涉及到頁面重定向。所以除非你想做一些AJAX風格的頁面加載,否則堅持使用標準的HTML。

對於任務,我用這個甜蜜的組合:

$('#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); 
       } 
     }); 
    }); 
} 

真棒,對不對?

這裏的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> 

有一個有趣的。