سؤال

I'm building my personal site and I've encountered a challenge. I suppose it will be none to those, who are more familiar with jQuery than me (not hard) ;)

The structure:

<a href>one</a>
<div id="hidden_one></div>

<a href>two</a>
<div id="hidden_two></div>

<a href>three</a>
<div id="hidden_three></div>

<a href>four</a>
<div id="hidden_four></div>

etc. In other words every "a" is shown all the time and has an attached div below.

The action:

After clicking any "a":

if clicked "a" has a shown div below - close the div

if clicked "a" doesn't have a shown div below, but there are other divs shown - hide those divs and show the one attached to this "a".

if no div is shown - show the one attached to this "a".

I'll be grateful for any support! :)

هل كانت مفيدة؟

المحلول 2

Probably best to use the href tag:

HTML:

<a href="hidden_one">one</a>
<div id="hidden_one">Hide 1</div>

<a href="hidden_two">two</a>
<div id="hidden_two">Hide 2</div>

<a href="hidden_three">three</a>
<div id="hidden_three">Hide 3</div>

<a href="hidden_four">four</a>
<div id="hidden_four">Hide 4</div>

JavaScript:

    $('a').on('click',function(e) {
        e.preventDefault();
        var href = $(this).attr("href");
        $("#" + href).slideToggle().siblings('div').hide();
    });

DEMO

نصائح أخرى

Try this

$('a').on('click',function(e) {
    e.preventDefault();
    $(this).next('div').slideToggle().siblings('div').hide();
});

DEMO

Well, you can do it the easy and fast way. Or you put in some extra effort and build up good HTML and go for safe. Look here: http://jsfiddle.net/veritas87/qLPge/2/

$(document).ready(function(){
    $('a.clickme').on('click', function(e){
       $('div.active').removeClass('active').fadeOut();
       $(this).next('.showme').addClass('active').fadeIn(); 
       e.preventDefault();
    });
});

Thank you! It works like charm :)

I've made a small modification:

$('a').on('click',function(e) {
    e.preventDefault();
    var href = $(this).attr("href");
    $("#" + href).slideToggle().siblings('div').slideUp();
});

http://jsfiddle.net/4qTeD/2/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top