tags:

views:

80

answers:

2

I have a list with links. These links are links to tables on the same page. What I want to do is whatever link I click in the list it will show its corresponding table and hide all the others.

Without adding a different id/class to each link in the list and its corresponding table, is there a way to find out which element was clicked and show() its table?

From what I understand JQuery returns an array object on its selector. How can I find out what element of the array was clicked?

I've tried to use event.which but I'm a little lost.

Help is greatly appreciated!

+1  A: 

CSS:

<style type="text/css">
    table {display:none;}
</style>

Script:

$(document).ready(function() {

        $.each($('a'), function(i) {

            var link = $(this);

            link.click(function() {

                $('table').hide().eq(i).fadeIn();
            });

        });
    });

html:

<ul>
    <li><a href="#">first</a></li>
    <li><a href="#">second</a></li>
    <li><a href="#">third</a></li>
</ul>

<table>
    <tr>
        <td>first</td>
    </tr>
</table>
<table>
    <tr>
        <td>second</td>
    </tr>
</table>
<table>
    <tr>
        <td>third</td>
    </tr>
</table>
XGreen
The poster specifically asked: "Without adding a different id/class to each link in the list and its corresponding table"
Nick Craver
i updated the post not to use any class name
XGreen
this works perfectly. but before i even implement this i'd like to understand how jquery does a few things. why must you use $.each($('a'), function(i){..}); ? and not just $('a').click(function() {}); .when you pass a parameter (in this case the variable "i") how do you know what it does? the only thing ive seen when passing a param to that kind of function is "event".. lastly, $('table').hide().eq(i).fadeIn();why should we call hide() again if its already hidden via CSS? why doesn't $('table').eq(i).fadeIn() work?sorry for the newbie questions, took a long hiatus in jquery.
centr0
+1  A: 

$('a').click attaches a single event to an element however each (equivalent of foreach in c#) iterates through all the matching elements of the selector

the each function has a built in feature that adds the "i" variable as index to these elements.

you could easily recreate it using for (i=0; i< bla.length; i++)... but each has all this inside it.

and finally I have set all the tables to be hidden in the css and used the hide function at the beginning of the chain cause if I don't for example table one as a result of clicking becomes display:block and then if I click the second link then the second table becomes visible as well as the first one which did not get hidden.

so the hide makes sure every table is hidden and the only the one that matches the index i becomes shown afterward.

XGreen
Thank you for taking the time to explain it to me! :)
centr0