简体   繁体   中英

How to check if the document is ready in JavaScript?

I am developing a simulator to simulate user actions in a Web page. In a special case, there are a few number of buttons in a page clicking on each changes the content of the page. I programmatically click on each button and then want to extract the new content added to the page. If you have a look at:

http://www.elementbars.com/Build-a-Bar-Service.aspx#

you can find an example.

My code is something like this:


for (var int i=0; i< buttonArray.length; i++){ // buttonArray is the array of buttons
    triggerClickEvent(buttonArray[i]);
    extractNewContent();
}

function triggerClickEvent (clickableElement) {
   jQuery(clickableElement).trigger('click');
}

Both triggerClickEvent and extractNewContent are properly working, but the problem is that after triggering the click event, the JavaScript engine should wait for a while to make sure that the new content is added, but it does not behave as expected. For example, I noticed that all the buttons are clicked, but extractNewContent extracts content for the first button, meaning the these two functions are not working synchronously. I used the setTimeout function, but since it does not block the execution, so could not resolve the problem. I also used functions checking the state of the document, but not working as well.

I would be grateful if you could please help me.

Thanks.

The easiest way to do it is with a toolkit like jQuery. Something like this:

jQuery(document).ready(function() {
...
});

or the more concise

jQuery(function() {

});

Part of the problem is that "ready" is not standardized across browsers. Toolkits like jQuery make up for that.

You can pass parameters to trigger function one of them would be a callBack function extractNewContent in our case. And call this function after all modifications are done in click event handler. So the handler would be

$(clickableElement).on('click', function(event, callback){
                       ...
                       all DOM modifications goes here
                       ...
                       if(typeof callback === "function")
                           callback();
                       }

and then trigger it with extractNewContent as parameter

$(clickableElement).trigger('click',extractNewContent);

The following code works:

for (var int i=0; i< buttonArray.length; i++){ // buttonArray is the array of buttons
  triggerClickEvent(buttonArray[i]);
  alert('balalalala'); // if you remove this, it won't work.
  extractNewContent();
}

function triggerClickEvent (clickableElement) {
 jQuery(clickableElement).trigger('click');
}

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