简体   繁体   中英

JQuery - $(document).ready() executing BEFORE element load

So, I'm loading some data from a MVC3 action that returns Json, containing some parameters and content as a string. I append the content to some div. In the partial view I have a document.ready JQuery event. For some reason that function executes before the content is appended and all the selectors I declare in the ready function are empty.

Is there a logic reason for this? Is I set a timeout the selectors see the elements. But a timeout can be very imprecise.

Any suggestions?

Thanks!

Example code fiddle: http://jsfiddle.net/aKxy7/

It sounds like you are expecting $(document).ready() to fire after all assests are loaded. That's not how $(document).ready() works. It is triggered when the DOM is finished rendering. Nothing more. It sounds like you want to use $(window).load() , which does wait until all assets are loaded.

$(document).ready() gets called when the HTML! is loaded. This means that if your HTML loads some javascript that makes changes to the HTML DOM, those $(document).ready() gets called before that.

You should either make sure your function is called last or use setTimeout that calls itself untill the elements you need are all loaded.

In your $(document).ready function you can call jQuery's $.ajax or $.getJSON to get the answer from your server. Then you can inject the json response where you want. No setTimeout needed

First off,

var elementIWannaGet = $('html-content-div');

should be

var elementIWannaGet = $('#html-content-div');

However, what you may be better off doing is separating the script from the content, as the dom is already loaded...

Consider changing the response to this:

{ result: true,
  data: { id: '1' },
  elementId: '#html-content-div',
  content: '<div id="html-content-div">Html content! :D</div>'
}

And then change your contentLoaded handler as follows:

function contentLoaded(response) {
    if (response.result == true)
        handleError(response);

    // Get the container where the response.content will be rendered to.
    var targetContainer = $('#target-container-id');

    // Append the content
    targetContainer.append(response.content);

    // Do something with your container
    alert( $(response.elementId).html().length );
}

我最终编写了一个方法,该方法一直等到通过ajax加载的HTML中的选定元素准备就绪。

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