admin管理员组文章数量:1391956
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 badges3 Answers
Reset to default 2I 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. Thedocument
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.
本文标签: jqueryBind ready event on javascript dom element creationStack Overflow
版权声明:本文标题:jquery - Bind ready event on javascript dom element creation - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744704102a2620736.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论