> Hi everyone, I've been playing with jQuery a lot lately but my skills
> could use a lot of work. I recently made this small snippet of script
> to show and hide tablerows from a link that looks like this:
>
> 1
>
> this will show:
>
>
> etc
>
>
> Javascript:
>
> $(function(){
> $('.box').hide(); /* hide every tr with class box at the start */
> $('.ahref',this).click(function () {
> var id = $(this).attr('href');
> $('.box'+id).toggle();
> $("tr.box:not('.box"+id+"')").hide(); /* so it will
> hide all the
> other TR's */
> return false; /* so it doesn't follow the link itself
> */
> });
> });
>
> Now I was wondering if anyone would like to critique it, I find it is
> a bit slow at times.
Is it the case that there could be multiple s with class 'box1'?
If that's a unique identifier for a row, I'd swap that to an ID
instead, which will simplify your code slightly and also not require
you to use fake hrefs:
HTML:
1
Now your JS can simply take the href and use it directly as a selector
to find which box to hide/show. You can also get rid of the :not
selection (which may be what's slowing things down) by first hiding
*all* .box rows then just showing the one you want, rather than hiding
after the fact:
$(function () {
var $boxes = $('.box').hide(); /* hide every tr with class box at
the start, and stash a reference to them for later use */
$('.ahref').click(function () {
$boxes.hide(); /* hide all the boxes again; something
might be showing from the last click */
$(this.href).show();/* this, in a click handler, is a
reference to the HTML element, so just grab its href without invoking
jQuery on it; its href is an anchored selector so it can be passed
right to jQuery */
return false; /* prevent default link behavior */
}
});
If your box #s are not unique (IOW, there could indeed be multiple
with the same class) then you need to keep your classes, but I'd still
stash the reference to $boxes initially, and not worry about the :not
matching--just hide everything first before you decide what to show.
In that case, I don't know a good solution to how to make the link
href meaningful; that depends somewhat on your data.