2012-01-22 45 views
1

我在這種類型的場景提供的各種答案環顧了很多(幾個小時),但我不是一個程序員,所以我得到卡在可能很簡單的事情上。情況如下:我有一個jQuery動態菜單(基於jquery lava lamp menu),它根據頁面上的項目ID定位導航圖像。此ID與URL的最後部分相匹配,在URL之前插入「primary-menu-」字樣。所以,我有:使用JQuery來選擇一個基於URL的動態ID

example.com/blog 
example.com/about 

用於上述網址列表項導航元件ID是:

id="primary-menu-blog" 
id="primary-menu-about" 

的(剪斷)jQuery代碼我必須選擇這些動態項(我從不同的答案類似的問題複製)是:

var url = '/'; 
var id = parseInt(url.split('/')[url.split('/').length - 1]); 
var nav = $(this), 
currentPageItem = $("#primary-menu-" + id, nav), 

我設法得到這種動態菜單上sample page工作不具有動態變化的標識。但自然,它不適用於新代碼,因爲我對此不夠了解。但我認爲我正走在正確的軌道上。建議最受歡迎。

編輯:在嘗試在此線程中實現建議後,沒有成功,我想我必須缺少一些簡單的東西。因此,爲了清楚起見,這裏充滿了腳本(這不是那麼長......):

(function($) { 
    $.fn.spasticNav = function(options) { 
    options = $.extend({ 
     overlap : 0, 
     speed : 500, 
     reset : 1500, 
     color : 'none', 
     easing : 'easeOutExpo' 
    }, options); 

    return this.each(function() { 
     # Added by Me, for testing on localhost; 
     var url = 'localhost:8000/'; 
     var id = url.split('/').pop(); 
     # End Added by Me. 
     var nav = $(this), 
     currentPageItem = $("#primary-menu-" + id, nav), 
     blob, 
     reset; 
     $('<li id="blob"></li>').css({ 
     width : currentPageItem.outerWidth(), 
     height : currentPageItem.outerHeight() + options.overlap, 
     left : currentPageItem.position().left, 
     top : currentPageItem.position().top - options.overlap/2, 
     backgroundColor : options.color 
     }).appendTo(this); 
     blob = $('#blob', nav); 
     $('li:not(#blob)', nav).hover(function() { 
     // mouse over 
     clearTimeout(reset); 
     blob.animate(
      { 
      left : $(this).position().left, 
      width : $(this).width() 
     }, 
     { 
      duration : options.speed, 
      easing : options.easing, 
      queue : false 
     } 
     ); 
     }, function() { 
     // mouse out  
     reset = setTimeout(function() { 
      blob.animate({ 
      width : currentPageItem.outerWidth(), 
      left : currentPageItem.position().left 
      }, options.speed) 
     }, options.reset); 

     }); 
    }); // end each 
    }; 
})(jQuery); 
+0

你如何告訴我們你實際上想要做什麼? – Sinetheta

回答

0

你甚至不必解析URL。你可以只使用一個屬性選擇器選擇任何元素的ID開始與primary-menu-

var currentPageItem = $(this).find('[id^="primary-menu-"]'); 

如果你絕對必須使用的網址,使用:

var id = window.location.href.split('#')[0].split('?')[0].split('/').pop(), 
    currentPageItem = $(this).find('#primary-menu-' + url); 
+1

對於添加動態內容,它仍不會做任何事情。直到他揭示他對這個選擇者的計劃是什麼,我們不能開始不可避免的「omg use .live()」「omg .live()被depracated」討論;) – Sinetheta

+0

感謝您的反饋。我想要做的是選擇(動態)ID。而已。當我使用諸如「selected」之類的靜態ID時,jquery代碼完美地工作:它在導航鏈接列表上滑動圖像並返回以確定「選定」。我改變的唯一的東西就是它選擇的東西。 – rosslaird

0

您可以提高你的代碼喜歡這個。

var url = 'example.com/blog'; 
var id = url.split('/').pop(); 
var nav = $(this), 
currentPageItem = $("#primary-menu-" + id, nav); 
+0

使用'url.split('/').pop()'而不是'url.split('/')。reverse()[0]'。 –

+0

@JosephSilber - 謝謝你完全忘了:P – ShankarSangoli