views:

32

answers:

1

I have a table which displays the Dynamic rows from server side script .Each rows conatins various values and the first row value contains the link such as "Show/Hide" when we click on "show" it shows the sub rows and when clicked on "hide" it hides the rows. Now the "Show/hide" is dynamic is such way their id is .where $i is dynamic value which takes (0,1,2..so on) Now how do we handle the click of "Show/hide" for each row

var j=0;
$("#mylink"+j).click(function(){


})

//In the above statemnt I can handle only "0th" link and how do we handle the links for 1 ,2 and so on.........

+3  A: 

Instead of an ID use a class, for example:

<a class="mylink" href="something.html">My Link</a>

Then use .live() instead of .click(), like this:

$(".mylink").live('click', function(){
  //do something, e.g. $(this).closest('tr').something();
});

.live() will listen for events from elements regardless of when there were added because the events bubble up to document by default. .click() is actually binding a click handler to the elements it found at the time, so doesn't work for future elements.

Nick Craver
This is what I've used in the past, but jQuery ninjas say that .live() is an inefficient method.. Any response to those claims?
melee
@melee - Inefficient as compared to what, searching the DOM for new elements every time they're added and dynamically binding a handler to *each*? For dynamic elements or large number of elements using a method based on event bubbling like `.live()` does is *much* more efficient.
Nick Craver
@nick:Really Awesome and interesting
Someone
@Nick Craver I'm not really familiar with what the .live() entails, but I was under the impression that it constantly checks the DOM for that element. Is it best practice? I've always wondered but never got a definitive answer.
melee
@melee - That's the `.livequery()` plugin which works differently...what `.live()` does is attach an event handler on `document` and listens for events that bubble (which they do anyway by default), when the event gets there it checks the target against the selector it's supposed to run the handler for.
Nick Craver
@Nick thank you for the clarification!
melee