【问题标题】:How to set event delegations on iframe load events in jquery?如何在 jquery 中的 iframe 加载事件上设置事件委托?
【发布时间】:2017-07-11 04:18:37
【问题描述】:

在jquery中,我基本上想这样做:

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

这可能吗?我想在 iframe 动态添加到 DOM 并完成加载时运行一个函数。

【问题讨论】:

  • 你检查this answer了吗?
  • 这是如何在我已经知道的特定 iframe 上设置它,但它与我的问题不同。
  • 您可以尝试将$('#theiframe') 更改为$("iframe")。我猜这应该适用于所有 iframe。
  • 这适用于所有 现有 iframe,但不适用于动态添加的新 iframe。

标签: jquery iframe event-delegation


【解决方案1】:

当一个新的 iframe 被动态添加到 DOM 时,您还必须为其动态创建一个新的事件处理函数。这是规则,没有什么可以改变的。

【讨论】:

    【解决方案2】:

    嗯,我相信这可以通过MutationObserver 和 jQuery 的事件绑定的组合来实现。

    您可以像这样将观察者注册到 DOM(示例代码借用自 here):

    $(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,就像我在上面所做的那样。

    完成后不要忘记不观察:

    observer.disconnect();
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多