簡體   English   中英

從動態創建的頁面將元素加載到文檔中時運行功能

[英]Run function when element is loaded into document from dynamically created page

我在這里讀到: jQuery的.on函數似乎不喜歡.load不起作用的'load'事件 ,“在所有瀏覽器中,load事件不會冒泡”。

我正在嘗試不使用$(function(){ta​​bs();}); 在需要“標簽”功能運行的每個頁面上。 那么,當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()的代碼。

簡單的樣機: http : //jsfiddle.net/TrueBlueAussie/z4GK7/3/

更簡單的版本。

您還可以將其他單獨的屬性對象傳遞給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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM