JQuery: which element was clicked?
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. H开发者_JAVA技巧ow 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!
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>
$('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.
精彩评论