0

I have a json array like this:

var headerStrings = [
        "Apple",
        "Banana",
        "Pineapple",
    ];

This is my HTML:

<div id="links">
    <ul>
        <li><a>One</a></li>
        <li><a>Two</a></li>
        <li><a>Three</a></li>
    </ul>
</div>

<div id="fruit">Mango</div>
<div>
    <div>Some content one</div>
    <div>Some content two</div>
    <div>Some content three</div>
</div>

When I click on the link 'One' I want to do two things:

  1. Replace the content of the DIV #fruit to the first item in the array - Apple.
  2. Show the first DIV(Some content one) and hide the other two divs

I want to do this for the other two links as well - when I click the link 'two', I want to show the DIV(Some content two) and replace the DIV #fruit to the second item in the array - Banana.

Here's what I tried:

var items = $('#links ul li');
items.click(function(event){
    event.preventDefault();
    var which = $(this).index();
    $('div').find('div').hide().eq(which).show();
    $('#fruit').innerHTML = data.headerStrings[which];
});

Thanks for your time.

b-marls
  • 307
  • 1
  • 5
  • 19

2 Answers2

1

DEMO

var headerStrings = [
    "Apple",
    "Banana",
    "Pineapple",
];

$('ul li a').each(function(i){
 $(this).click(function(){
     $('#fruit').html(headerStrings[i]);
     $('#content').children().hide().eq(i).show();
 });
});


<div>
<ul>
    <li><a>One</a></li>
    <li><a>Two</a></li>
    <li><a>Three</a></li>
</ul>

<div id="fruit">Mango</div>
 <div id='content'>
 <div>Some content one</div>
 <div>Some content two</div>
 <div>Some content three</div>
</div>​​​
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
0

You can use jquery templates to solve this.

Introduction to jquery templates will get you started.In summary , you will load all the div's and hide it, then show/hide the div according to the click. There is a jquery toggle div method for this.

Community
  • 1
  • 1
Tito
  • 8,894
  • 12
  • 52
  • 86