开发者

jquery and ajax problem

开发者 https://www.devze.com 2023-01-31 12:13 出处:网络
i am using jquery and ajax. i have some divs with ids like id=\"apple-23\" , i开发者_StackOverflow社区d=\"apple-45\" and ...

i am using jquery and ajax.

i have some divs with ids like id="apple-23" , i开发者_StackOverflow社区d="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?


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);
 });


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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消