-4

Case1: List is present in the html already

<ul id="list1">
    <li>One</li>
    <li>Two</li>
</ul>

The clicked li element is detected using

$('#list1 li').bind('click', function(){
   alert($(this).html());
});

Above works fine.

Case 2:

Now if the list is added dyamically

<div id="testDiv">
</div>

var output = '<ul id="list1">' +
             '<li>One</li>' + 
             '<li>Two</li>' +
             '</ul>';

$('#testDiv').html(output);

I try to detect the clicked li element using same code

$('#list1 li').bind('click', function(){
    alert($(this).html());
});

In this case, it does not detect

user544079
  • 13,851
  • 35
  • 102
  • 160

1 Answers1

4

Assuming that you've got jQuery correctly loaded, and that you put your jQuery related code in a "document ready" handler, I'd recommend "event delegation", such that you just register a single event handler on a static ancestor element.

Clicks received in the li descendants will "bubble up" to the ancestor element, but jQuery will ensure that this is set to the element that was actually clicked:

$('#testDiv').on('click', 'li', function() {
    console.log(this);
});

So long as the static ancestor remains present on the page you can dynamically change its contents as much as you please and the event handler will continue to work.

Alnitak
  • 313,276
  • 69
  • 379
  • 466