简体   繁体   中英

Altering elements that are loaded from buttons after the page itself is finished loading

I realize the title is a bit unclear, so I'll elaborate as well as possible. Essentially, there is a webpage that the user visits. After the page completes its initial load, the user may then click a button on the page which will load new content into the page. Something like <div class="expanded" style> -- basically a bunch of text and perhaps some links.

I essentially need to alter the contents of this newly loaded area. Right now, I am running something like:

$('div.expand-button').click(function(){ //When the button to load new content is clicked...

And then fire off my document.querySelectorAll function at this point. However, if I do this, the new content is not finished loading when the function runs, and, as a result, nothing happens. What's the best way of delaying my function so that it will only run after the new content area is loaded?

I had a similar problem recently and the simplest solution I found (albeit probably not the best) was to use setTimeOut. So your code would look something like :

$('div.expand-button').click(function(){ 
YourLoadNewAreaFunction();
setTimeout(function() {
            //do stuff you needed the page completely loaded to do
        }, 1000);
}

1000 is of course an arbitrary number of milliseconds I chose, you could choose whatever time you deem necessary to completely load your new area. Assuming your new content loads in under a second, the above should work.

From what I've seen online, you could also try looking into callbacks.

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