It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.
Here's the fiddle: link.
What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>
s with class="cat1"
or class="cat2"
.
I also mark the links with a simple .toggler
class. It's not good practice to have onclick
attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.
$(".toggler").click(function(e){
// you handle the event here
});
With this format, you are binding an event handler to the click
event of links with class toggler
. In my code, I add a data-prod-cat
attribute to the toggler
links to specify which product rows they should control. (The reason for my using a data-*
attribute is explained here. You can Google 'html5 data attributes' for more information.)
In the event handler, I do this:
$('.cat'+$(this).attr('data-prod-cat')).toggle();
With this code, I'm actually trying to create a selector like $('.cat1')
so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat')
this to access the data-prod-cat
attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible
like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggle
s the visibility of the specified element(s).
I hope this was explanatory enough.