-2

有类似的代码可以工作,只是不能让它与这个实例一起工作。

使用 jquery 更改链接上方 div 的 CSS 以隐藏 subnav ( currently stays open because link href="#")。

所有链接都有“团队”类,一旦单击其中任何一个,应将 subnav 更改为 display="none"

代码是:

$('a.team').click(function() {
    $('.subnav', this).css('display','none'); 
});

jsfiddle:http: //jsfiddle.net/a9AYE/

4

2 回答 2

0

你提到

使用jquery更改链接上方div的CSS隐藏subnav

所以,猜测,你HTML是这样的

<div class="subnav">Div Above the link One</div>
<a class="team" href="#">Link One</a>
<div class="subnav">Div Above the link Two</div>
<a class="team" href="#">Link Two</a>

所以,你可以使用这样的东西

$('a.team').click(function(e) {
    e.preventDefault();
    // Hide the div with class ".subnav" that is right above/brfore this link
    $(this).prev('.subnav').css('display','none'); 
});

演示。

P/S:你也应该发布你的HTML

于 2013-08-10T01:32:06.150 回答
0

You are supposed be using closest (As subnav is the ancestor of .team elements)

$(this).closest('subnav').css('display', 'none'); 

  

It is a better idea to use a class to change the style instead of defining them inline

.hide{
    display: none;
}

Just add a class to apply the specific class. Lot more cleaner and less messy.

Also prevent the default action of the link being followed.

$('a.team').click(function (e) {      
    e.preventDefault();
    $(this).closest('.subnav').addClass('hide')
});
// This is to remove the hide class
// which has more specificity
$('.nav > li').mouseover(function (e) {   
    $('.subnav').removeClass('hide')
});

You will encounter specificity issues in this example.

When you set display:none inline you can only override it by specifying inline again.

Use classes instead. And you see the same issue again. But writing a more specific class should solve the issue.. And your CSS should look like below for it to work.

CSS

.nav > li .subnav {
    display:none;
}
.nav > li:hover .subnav {
    display:block;
}

.nav > li .hide.subnav{
    display: none;
}

Check Fiddle

于 2013-08-10T01:34:02.007 回答