jQuery:如何在尚未添加到DOM的元素上调用jQuery插件函数? [英] jQuery: How to call a jQuery plugin function on an element that hasn't yet been added to the DOM?
本文介绍了jQuery:如何在尚未添加到DOM的元素上调用jQuery插件函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个我正在使用的jQuery插件:
I have a jQuery plugin that I am using:
$(document).ready(function(){
$('.elements').fancyPlugin();
});
这在我开始添加新元素之前效果很好:
This works great until I start adding new elements:
$.get('ajax.html', function(data){
$('#container').html(data);
});
我可以再次调用插件函数:
I could call the plugin function again like this:
$.get('ajax.html', function(data){
$('#container').html(data).find('.elements').fancyPlugin();
});
...除了AJAX发生在另一个不应该知道的jQuery插件中 fancyPlugin()
。
...except that the AJAX is happening inside another jQuery plugin that shouldn't have to know about the fancyPlugin()
.
如何将此插件应用于所有当前和未来的元素?
How can I apply this plugin to all current and future elements?
推荐答案
我认为这适用于IE以外的所有浏览器:
I think this will work in all browsers except IE:
document.body.addEventListener("DOMNodeInserted", function(event){
var $elementJustAdded = $(event.target);
if ($elementJustAdded.hasClass('elements')) {
$elementJustAdded.fancyPlugin();
}
}, false);
这篇关于jQuery:如何在尚未添加到DOM的元素上调用jQuery插件函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文