问题描述:

I am learning recently about javascript, but right now I am stuck for 2 days with an easy (i think) problem! I hope I can find some help here.

I want to create a small vertical navigation with three "toggle" buttons in form of images to show different content.

Basically if you click on a "toggle" button, content will be placed on the right side of the navigation.

The problem is that I want to change the image ("toggle" button) if it got clicked. And more important change it back again when another button gets clicked.

this is my recent code to show the content on the right side:

$('.parent div').hide();

$('.parent div.a').show();

$('#mini-nav img').click(function () {

console.log($(this).index('img'));

var $div = $('.parent > div').eq($(this).index('#mini-nav img'));

$div.show();

$('.parent > div').not($div).hide();

});


 <div id="mini-nav">

<img src="http://placehold.it/80x80"/>

<img src="http://placehold.it/80x80"/>

<img src="http://placehold.it/80x80"/>

<img src="http://placehold.it/80x80"/>

</div>

<div class="parent">

<div class="a">

<p>this is a</p>

</div>

<div class="b">

<p>this is b</p>

</div>

<div class="c">

<p>this is c</p>

</div>

<div class="d">

<p>this is d</p>

</div>

网友答案:

You can do something like:

$('#mini-nav img').click(function() {
    // Mark all nav images as not selected
    $('#mini-nav img').removeClass('selected');

    // Hide all images
    $('.parent > div').hide();

    // Show the one the user wanted and set the class on the button
    var $btn = $(this);
    var index = $btn.index('#mini-nav img');
    $('.parent > div:eq(' + index + ')').show();
    $btn.addClass('selected');
});
相关阅读:
Top