创建元素时的 jQuery 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9262677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery event when element is created
提问by rpophessagr
I'd like to trigger an event when an element is created.
我想在创建元素时触发一个事件。
$(document).on('load','#TB_title',function() {
console.log('loaded');
});
Is there an equivalent of this that works?
有没有等效的方法?
I saw some people suggest livequery, but that seems heavy.
我看到有些人建议使用 livequery,但这似乎很重。
Thanks.
谢谢。
回答by Shadow Wizard is Ear For You
I don't think such thing exist directly, but you can handle the DOMSubtreeModified
event and wait until you can find element with such ID:
我不认为这样的东西直接存在,但是您可以处理DOMSubtreeModified
事件并等待找到具有此类 ID 的元素:
var _elementToFind = "TB_title";
var _elementFound = false;
var _counter = 1;
$(document).bind("DOMSubtreeModified", function(evt) {
if (_elementFound)
return;
if ($("#" + _elementToFind).length > 0) {
alert("element '" + _elementToFind + "' created");
_elementFound = true;
}
});
The downside is that it's not supported by Opera and IE less than 9 - see herethe full details.
缺点是 Opera 和 IE 不支持小于 9 -请参阅此处的完整详细信息。
回答by osahyoun
You can trigger a global custom event:
您可以触发全局自定义事件:
$(document).on('load','#TB_title',function() {
$.event.trigger('nameOfCustomEvent');
});
$('#element').bind('nameOfCustomEvent', function(){
console.log(this);
});