Javascript 显示当前子菜单并隐藏其他子菜单
我试图使当前子菜单保持活动状态,并隐藏其他子菜单,但无法理解Javascript 显示当前子菜单并隐藏其他子菜单,javascript,jquery,html,Javascript,Jquery,Html,我试图使当前子菜单保持活动状态,并隐藏其他子菜单,但无法理解this关键字是如何工作的。当前,由于$('.nav second level').show()的原因,当单击任何子菜单的链接时,所有子菜单都保持活动状态我认为这里我需要修改,但无法理解如何修改。我是一个jquerynoob HTML 试试这个: $(document).ready(function() { // hide all second level $('.nav-second-level').hide();
this
关键字是如何工作的。当前,由于$('.nav second level').show()的原因,当单击任何子菜单的链接时,所有子菜单都保持活动状态代码>我认为这里我需要修改,但无法理解如何修改。我是一个jquerynoob
HTML
试试这个:
$(document).ready(function() {
// hide all second level
$('.nav-second-level').hide();
// show all second level whose anchor has matching href
$('a').each(function(){
if(document.location.href.indexOf($(this).attr('href')) > 0)
{
// add class to matching anchor
$(this).addClass('active-me');
// find its parent 'nav-second-level' and make visible
$(this).closest('.nav-second-level').show();
}
});
// open submenu on click of main menu
$('a[href="#"]').click(function(){
$('.nav-second-level').hide();
$(this).next('.nav-second-level').show();
});
});
使类的整个链接处于活动状态,所有子菜单都可见document.location.href
在您的情况下,因为这里您只是检查匹配值,而不是精确值。我错过了if(…>0)
在if条件下与零的比较。对不起,我的错误,我只是从你的代码复制并粘贴它。请尝试更新答案。还添加了演示链接:)几乎工作正常,只是当我试图打开另一个子菜单时,它不允许我打开,我使用的是:。在这个代码(插件)之后,我将代码发布在stackoverflow上。非常感谢您的帮助。单击主菜单时是否打开其他子菜单?
$(document).ready(function() {
var aObj = $('a');
var found = false;
for(var i=aObj.length-1; i>=1 && !found; i--) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
$(aObj[i]).addClass('active-me');
found = true;
}
}
var submenulink = $('.nav-second-level > li > a');
if(submenulink.hasClass('active-me') == true){
$('.nav-second-level').show();
}
});
$(document).ready(function() {
// hide all second level
$('.nav-second-level').hide();
// show all second level whose anchor has matching href
$('a').each(function(){
if(document.location.href.indexOf($(this).attr('href')) > 0)
{
// add class to matching anchor
$(this).addClass('active-me');
// find its parent 'nav-second-level' and make visible
$(this).closest('.nav-second-level').show();
}
});
// open submenu on click of main menu
$('a[href="#"]').click(function(){
$('.nav-second-level').hide();
$(this).next('.nav-second-level').show();
});
});