jQuery make loaded file part of DOM
I've loaded file in div
$("#div").load("file.txt");
That file has html images .
I want to access them by $('#div>img') (or other selectors), but nothing happens. If they were in page initially, there are no problems.How can you access loaded content by jQuery as part of the usual page?开发者_StackOverflow
See jquery doesn't see new elements for one possible problem you might be having. Use the change
method to wait until they enter the DOM. e.g.
$("#div").load("file.txt");
$('#div>img').change(function(){
var images = $('#div>img');
// Do something...
}
The content loaded (supposedly through Ajax) is rendered as a text string. It's up to you to load it into the DOM using .innerHTML and such. In jQuery you can use .html()
to load the content inside the DOM and then you're going to be able to access it through standard jQuery DOM selectors.
$("#div").load("file.txt");
$("#div > img")... // file.txt hasn't finished loading yet
Will probably not work, since loading the file happens asynchronously and takes some time, and the content is simply not there yet when you try to access it. For this reason, you can specify a callback that is guaranteed to run after the load()
has finished:
$("#div").load("file.txt", function () {
// file.txt has finished loading, this should work:
$("#div > img")...
});
精彩评论