开发者

jQuery can't access elements loaded through AJAX

I hav开发者_运维百科e a little application written in PHP. The front-end uses jQuery and AJAX. At one point, jQuery loads some content in through AJAX. The problem is, it can't then access any of the elements it just loaded. Anyone know why?

Thanks in advance!


@Ryan, in your jQuery are you trying to access the elements as fresh elements or are you expecting events to already be bound to the elements?

i ask because if you have say a span that has a click event attached to it, when you load a new one that new span won't have a click event yet. you'll need to bind one or use i think the .live keyword to always have spans, even spans created later, bind to the same events.

It would help if you had a small sample of your html before, after and the jquery you are running so we can see and debug for you.


Javascript is typically synchronous, but AJAX calls are by default asynchronous.

The upshot is that if you're trying to access the data that was returned and added to the DOM directly after the AJAX call, it is likely that that code has run before the AJAX response was received. As such, it seems like the data is inaccessible.

The solution is to do your manipulations in the success callback to the AJAX call.

$.ajax({
    url: "some/path/to/data",
    success: function( data ) {
        // Add returned data to DOM
        //   and manipulate data as needed
    }
});

// Can't access returned data here because this code
//    has likely executed before the response was returned.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜