I have some divs created dynamically this way:
//here goes some loop, and everything works fine
$("#result_main_search").append('<div class="singleresult_main_search">
<a href="http://somesite.com/" class="linktosight">'
+ SightsList[i]+ '</a> – ' +
'<img src="/images/balloon.gif" rel="'+ i
+'" class="balloon_img_main_search" /></div>');
After that loop, I try to set href attribute for each link:
$('.singleresult_main_search').each(function() {
$.get("_ajax_get_sight_link.php", {'id':$("img", this).attr('rel')},
function(data) {
alert($(this).find('.linktosight').length);
$(this).find('a').attr('href', data);
alert(data);
});
})
_ajax_get_sight_data.php
accepts id, returns link ( alert(data) works fine) .
But alert which tells how much .linktosight elements are in current div always gives 0 (开发者_高级运维by saying always I mean everytime it finds one of my generated divs). I've tried .size()
, $(this).find('a')
with the same result. So, how am I to set it to work?
this
inside the callback will point to the jqXHR-object and not to the looped elements.
You may create a closure:
$('.singleresult_main_search').each(function() {
var $this=$(this);
//.....
});
..and use it inside the callback:
function(data) {
alert($this.find('.linktosight').length);
});
$.proxy() may also be an option like suggested by Jack Franklin
精彩评论