我已经为这种情况提供了各种各样的答案(现在几个小时),但我不是程序员,所以我会陷入可能非常简单的问题。情况就是这样:我有一个jquery动态菜单(基于jquery lava lamp menu),它根据页面上项目的ID定位导航图像。此ID与URL的最后一部分匹配,在URL之前插入“primary-menu-”字样。所以,我有:
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没有动态更改ID。但很自然,它不适用于新代码,因为我对此并不了解。但我认为我走在正确的轨道上。建议最受欢迎。
编辑:在尝试在此线程中实现建议后,没有成功,我认为我必须遗漏一些简单的东西。因此,为了清楚起见,这里是完整的脚本(它不是那么久......):
(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 :(得分: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 :(得分:0)
您可以像这样改进代码。
var url = 'example.com/blog';
var id = url.split('/').pop();
var nav = $(this),
currentPageItem = $("#primary-menu-" + id, nav);