简体   繁体   中英

Can't do anything with .load()-ed content in jQuery?

I'm facing an interesting problem where everything works flawlessly. I console.log every step and it plays out just the way it should. But! I have a #div into what I .load(a-file.php). Now that "a-file.php" includes HTML mark-up as well, more specifically certain links that I'd like to make "active" onload.

Scenario; page load happens, Javascript loads and loads a file into the div. That div now has tabs and I'd like the first tab to be in an "active" state which requires me to addClass('active');. But the following seems to have no effect

$('#content').load('file.php'); // works.
$('#content a[rel="weird-page"]').addClass('active'); // does not work.

Any kind of help, even remotely nailing it, is appreciated.

change to:

$('#content').load('file.php', function() {
   $('#content a[rel="weird-page"]').addClass('active');
}); 

jQuery load() works asynchronously and therefore your addClass() method is being called before load() has completed.

Using the load() callback function it will ensure your content has loaded:

$('#content').load('file.php', function() {
   $(this).find('a[rel="weird-page"]').addClass('active');
});

shameless-plug-warning: I wrote a blog post about jQuery callback functions which you might find useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM