1

i am using jquery and ajax.

i have some divs with ids like id="apple-23" , id="apple-45" and ...

i have some jquery code like this:

 $("[id^=apple]").click(function(){
     elid = $(this).attr('id').split("-");
     pid = elid[1];
     alert(pid);
 });

the code works well for these divs.

but the ajax also return similar divs with similar id pattern like id="apple-61" and etc. but the jquery code doesn't work for these ajax produced divs.

why is it so? and how can i solve it?

hd.
  • 17,596
  • 46
  • 115
  • 165

2 Answers2

5

The problem is that you are binding the event before the elements exist.

Use live instead (assuming you are using jQuery 1.3+):

$("[id^=apple]").live("click", function(){
     elid = $(this).attr('id').split("-");
     pid = elid[1];
     alert(pid);
 });
Shurdoof
  • 1,719
  • 13
  • 16
3

You can use either .delegate() or .live() to handle events on elements that don't exist yet.

If these divs have a common parent, it's more efficient to use .delegate() instead of .live() (see here).

$("#divContainer").delegate("[id^=apple]", "click", function(){
     elid = $(this).attr('id').split("-");
     pid = elid[1];
     alert(pid);
});
Community
  • 1
  • 1
sje397
  • 41,293
  • 8
  • 87
  • 103
  • so if i have a parent for them using delegate() is more faster than live().because live attached to document and check the whole document to detect matched elements but delegate() only check some specific elements to find matched elements to attach event.is it right? – hd. Dec 19 '10 at 06:45
  • @hd: Yes, that's how I understand it. From that link, `delegate` actually calls `live` but limits its scope to the container, whereas `live` on it's own just delegates to the document. – sje397 Dec 19 '10 at 06:49