最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Bind ready event on javascript dom element creation - Stack Overflow

programmeradmin1浏览0评论

i would like to know if we can bind a loaded or ready event on an item created by a script when the dom is loaded. I heard from live() but it's not something clickable, it's just an item which has to load.

Thanks for your help!

i would like to know if we can bind a loaded or ready event on an item created by a script when the dom is loaded. I heard from live() but it's not something clickable, it's just an item which has to load.

Thanks for your help!

Share Improve this question asked Aug 16, 2010 at 14:50 ArtusamakArtusamak 611 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

I guess your best shot is the load event there.

$('element').load(function(){
   alert('loaded');
});

native

var elem = document.getElementById('element_id');
elem.onload = function(){
   alert('loaded');
};

Another example for dynamic creation:

$('<img/>', {
   src:   '/images/myimage.png',
   load:  function(){
     alert('image loaded');
   }
}).appendTo(document.body);

If you want to be able to separate the pieces of code for creating the item and the load event handling you could try having your dynamically created element trigger a custom event on the window:

var myElement = $('<img/>', {
   src:   '/images/myimage.png'
}).appendTo(document.body);

$(window).trigger( {type: "myElementInit", myObject : myElement} );

With a pointer back to itself in the extra parameters, you could then have a separate handler set-up within a jQuery(document).ready to look for the "myElementInit" window event and grab the reference to the element out of the extra parameters:

jQuery.('window').bind( "myElementInit", function(event){
  var theElement = event.myObject;
...
} );

You can use the delegated form of the .on() event, as documented here:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

发布评论

评论列表(0)

  1. 暂无评论