views:

73

answers:

3

hi,

i have a unordered list of links, which are dynamically created by Ajax, and for each link i want to add click function to it, but it won't work, please help!

here is my code:

HTML:

<div id="sidebar">
  <li>
      <h2> list </h2>
      <ul id="list"></ul>
  </li>
</div>

JS:

//to create links
var str = '';
$.each(json.opts, function(i, opt) {
  var id = opt + '-list';
  str += '<li><a href="#" id='+ id +'>' + opt + '</a></li>';   //link
}
$("#list").html(str);

...
//to add click function to each links, this won't work
$("#list li").each(function (i) {
   alert(i + " : " + $(this).text());
});
A: 

maybe you need .live()

Description: Attach a handler to the event for all elements which match the current selector, now or in the future.

Vince
A: 

It should be .click() instead of .each():

$("#list li").click(function (i) {
   alert(i + " : " + $(this).text());
});

And if you call this function, the elements must already be inserted. Otherwise you have to use .live():

$("#list li").live('click', function (i) {
   alert(i + " : " + $(this).text());
});
Felix Kling
thanks, the .live() did the trick!
Ohana
A: 

I've been fighting this all day!

.live() is what I needed.

I had dynamically created slide number links that weren't responding to .click()

thomasrye