Reputation: 33
I'm just getting started with jquery.
I have 3 divs with a class of .linkCol which each contain a lot of links.
I have been manually setting the id of the links but I know this is going to be a problem in the future.
If you look what i have so far, I have had to add an id manually to all my links.
var ttlLinks = $(".linkCol li").size();
for(i=1; i<ttlLinks;i++){
$('#'+i).click(function() {
hide(this);
});
}
So, I want to select all the links, loop through them and give each an individual id. how do I go about this? cheers Neil
EDIT:
Hi, I will post all my jquery so that you can see what i'm tring to do. It will hopefully make more sense then:
$(function() {
$('.txtToggle').hide(); // hide all text areas
$('#txt1').show(); //show the 1st one
var ttlLinks = $(".linkCol a").size();
for(i=1; i<=ttlLinks;i++){ $('#'+i).click(function() { // I have manually set each link id, i want this to be dynamically done hide(this); }); }
function hide(me){
$('.txtToggle').hide(); // hide all text boxes
var id = $(me).attr('id');
var showDiv = '#txt'+ id;
$(showDiv).show(); // show the one needed
}
});
in order to get this to work I have had to give each link on my page an id of 1, 2, 3, 4, 5 etc, as that value is used to select the correct content div later on. Is there a better way of doing this? its a simple show hide, but with LOTS of things to show and hide!
Upvotes: 1
Views: 1286
Reputation: 1305
$('.linkCol li').click( function() {
$(this).hide();
}
Now every li
that is a child of an element with the class linkCol
has the click event.
jQuery will loop through all the elements implicity. Just select everything you want the .click
to apply to and set the event.
If you want the ID for some other reason you can do as SLaks does below. Note that jQuery methods return the jQuery object they were called on, hence .click()
is chained onto .attr()
. However you probably don't need the ID's. .each()
passes the index of each element it iterates over to its callback, which is basically what your ID's are doing.
If you want a particular element in the list you can select them all and use .eq()
like so: $('.linkCol li').eq(3)
which selects the fourth element in the collection and returns a jQuery object containing just that element. If you want the element itself use array syntax on the jQuery object like $('.linkCol li')[3]
which gives you the fourth li
in the collection as a DOM object.
What I'm getting at is that sequential ID's like you're using should rarely if ever be necessary when using jQuery.
Upvotes: 1
Reputation: 887547
You can use jQuery's each
method:
$('.linkCol li').each(function(index) {
$(this).attr('id', index)
.click(function() { ... });
});
Upvotes: 2