开发者

Html is rendered event

I'm appending some code to my page using jQuery AJAX calls. This code is a mix of html and javascript. But I want javascript to be executed only when html part is ready.开发者_如何学运维 But what event is raised when appended html is rendered?

Here is an example:

<table id="sampleTable">
   ...
</table>

<script>
  // this code should be executed only when sampleTable is rendered
  $('#sampleTable').hide();
</script>


Use the jQuery ready() event:

$(document).ready(function() {
    $('#sampleTable').hide();
}

<edit> It seems to be impossible to call a ready event on any other object than Document, my bad </edit>

This is an option if you are talking about the event triggered after a successful Ajax request :

$('#sampleTable').ajaxComplete(function() {
    $(this).hide();
});

Or just hardcode the style of the table to display:none;...


Wrap your javascript in a "ready" handler. This will fire when the DOM has been updated and is undoubtedly what you want to do.

 $(function() {
     $('#sampleTable').hide();
 });


$(document).ready(function() {
    $('#sampleTable').hide();    
});

http://api.jquery.com/ready/


You're loading both the <table> and the <script> into the document at once? Don't.

Inserting HTML with <script> elements into the page using html()/load() is highly unreliable. The script doesn't run directly from innerHTML inclusion; different browsers treat such inserted script elements differently. jQuery attempts to fix some of this but doesn't quite get it quite right (it may not be possible to get it quite right).

It's best to keep your static code in static script, so that the caller knows it has to call hide() on the table just after the AJAX call completes and the content is inserted. If you really have to pass back dynamic code to run, keep it separate from the HTML, eg. by returning a JSON object with both HTML and code members.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜