2

I've got a minor problem with jQuery. In the HTML, I've got four links. I'm using addClass() and removeClass() to indicate which link has been selected, and that's working fine. However, I've got one specific link, #gallery, which initiates a slideToggle() with a div below the list. The thing is, if the div is showing, and the user selects a different link, the .selected class changes properly, but the div #book doesn't close. Any thoughts on how to resolve this? I've included all the code below, but (I've got a fiddle going here, which is probably a lot easier.

Thanks in advance!

HTML

<ul>
<li><a class="link" href="#">Click here</a></li>
<li><a class="link" id="gallery" href="#">Click here</a></li>
<li><a class="link" href="#">Click here</a></li>
<li><a class="link" href="#">Click here</a></li>
</ul>
<div id="book"></div>

CSS

.link:link, .link:visited { text-decoration:none; }

#book { width:100px; height:100px; background:blue; }

.selected { color:red; }

JS

var $book = $('#book');
var $gallery = $('#gallery');

$book.hide();
$('a').click(function(){
$('a.selected').removeClass('selected');
$(this).addClass('selected');
});

$gallery.toggle(
function(){$book.slideDown('slow');},
function(){ 
    $book.slideUp('slow');
    $gallery.removeClass('selected');        
});

​</p>

4

1 に答える 1

0

toggleメソッドは非推奨です。slideToggle代わりに使用できます。if ステートメントを使用できます。また、ターゲットがギャラリー スライドの ID を持つ要素でない場合は、その要素を使用できます#book

$('a').click(function(e) {
    $('a.selected').removeClass('selected');
    $(this).addClass('selected');
    if (e.target.id != 'gallery') $book.slideUp('slow');
});

$gallery.click(function() {
    $book.slideToggle('slow');
});

http://jsfiddle.net/Z244D/

于 2012-10-07T03:49:20.123 に答える