[英]Dynamically created iFrame is null when called from a page loaded by JQuery
[英]Run function when element is loaded into document from dynamically created page
我在这里读到: jQuery的.on函数似乎不喜欢.load不起作用的'load'事件 ,“在所有浏览器中,load事件不会冒泡”。
我正在尝试不使用$(function(){tabs();}); 在需要“标签”功能运行的每个页面上。 那么,当div .tabswrap类加载到文档中时,如何从页面运行函数?
动态加载的页面具有一个名为“ tabswrap”的div类:
选项卡功能:
function tabs(){
//do something
}
如果我将脚本放在动态加载的页面本身上(这是我要避免的操作),这确实可行:
<script>
$(function(){
tabs();
});
</script>
这些不起作用:
$('.tabswrap').on('load', function(){
tabs();
});
$('.tabswrap').load(function(){
tabs();
});
在加载动态内容并执行操作时,您可以通过触发器触发自己的事件。
var data=".myclassname";
$('body').trigger('tabswrapOnLoad');
....
$('body').on('tabswrapOnLoad', data, function(){ do stuff });
我从您的故事中得到的是,您使用div.tabswrap加载动态内容,并且每当加载新内容时,您都想执行tabs()函数,对吗?
它不起作用的原因是您试图绑定到尚不存在的元素。 您只能绑定到存在的元素上的事件。 此外,当您将节点插入dom中时,也不触发加载事件,因此即使在dom更新后也无法正常工作。 尝试类似:
<script>
function tabs() {
// something
}
function loadNewContent() {
// get dynamic content from somewhere
$('.content').html(newContent);
if ($('.tabswrap', $(newContent)).size() > 0) {
tabs();
}
}
</script>
正如我在评论中所说:我们必须为需要任意应用于加载页面的一组插件解决此问题。
解决方案:我们在Ajax加载中触发了自己的“ panel.loaded”事件,并将新面板作为属性传递。 顶级页面代码捕获panel.loaded事件,并基于已加载页面中的匹配类来应用插件。
在您的Ajax负载中:
var e = jQuery.Event("panel.loaded", {$panel: data});
$(document).trigger(e);
在您的母版页内:
$(document).on('panel.loaded' function(e){
// 1) Find a specific part of the loaded panel
tabs(e.$panel.find('.tabswrap'));
// Or 2) simply pass the loaded panel to tabs
tabs(e.$panel);
// Or 3) you don't really care about the panel loaded and
// will simply apply tabs again to the entire page
tabs();
});
此实现暗含一个tabs()的版本,该版本可以将已加载的面板作为参数。 否则,它可能会重新应用于整个页面。 那是您的电话,因为您没有提供tabs()
的代码。
您还可以将其他单独的属性对象传递给trigger
,而无需创建Event
对象。
$(document).trigger("panel.loaded", {$panel: data});
并用于:
$(document).on('panel.loaded' function(e, params){
// 1) Find a specific part of the loaded panel
tabs(params.$panel.find('.tabswrap'));
// Or 2) simply pass the loaded panel to tabs
tabs(params.$panel);
// Or 3) you don't really care about the panel loaded and
// will simply apply tabs again to the entire page
tabs();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.