2017-07-11 61 views
1

jQuery中,我想基本上做到這一點:如何設置jQuery中的iframe加載事件的事件委託?

$(window).on('load', 'iframe', function() { 
    alert(this); 
}); 

這是可能的嗎?我希望在iframe動態添加到DOM時運行一個函數,並完成加載。

+0

你檢查[這個答案](https://stackoverflow.com/a/24604300/2019247)? – 31piy

+0

這是如何將其設置在特定的iframe上,我已經知道,但它不同於我的問題。 – omega

+0

您可以嘗試將'$('#theiframe')'更改爲'$(「iframe」)''。這應該適用於所有iframe,我猜。 – 31piy

回答

0

當新的iframe動態添加到DOM時,您還必須動態創建一個新的事件處理函數。這是規則,沒有什麼可以改變這一點。

0

嗯,我相信這可以通過組合MutationObserver和jQuery的事件綁定來實現。

可以觀察者註冊以這樣的(從here借用樣本代碼)的DOM:

$(function() { 
    var target = document.querySelector('body'); 

    var observer = new MutationObserver(function(mutations) { 
    mutations.forEach(function(mutation) { 
     // Check if nodes are added 
     if (mutation.addedNodes.length > 0) { 
     mutation.addedNodes.forEach(function(node) { 
      // Check if the added node is an iframe 
      if (node.nodeName === "IFRAME") { 
      $(node).on("load", function() { alert("hello from iframe"); }); 
      } 
     }); 
     } 
    }); 
    }); 

    // configuration of the observer (need to research more on this) 
    var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
    }; 

    // pass in the target node, as well as the observer options 
    observer.observe(target, config); 
}); 

上面將觀察在DOM的變化,並且將動態檢查添加元素到DOM。

我相信您可以利用此功能將運行時事件綁定到添加的iframe,就像我上面所做的那樣。

只是不要忘記你這個做後unobserve:

observer.disconnect();