【问题标题】:Make iframe listen to same event as parent and synchronize using jquery使 iframe 监听与父级相同的事件并使用 jquery 同步
【发布时间】:2011-09-06 06:13:34
【问题描述】:

我在同一个域的 html 页面中有两个 iframe

<body>
  <table border="1" width="100%" height="100%">
    <tr>
      <th><iframe class="isiframe" width="100%" height="100%" src="/example"></iframe></th>
      <th><iframe class="isiframe" width="100%" height="100%" src="/example"></iframe></th>
    </tr>
  </table>
</body>

我已经为 iframe 内网页中的所有 a 标签提供了点击事件

$('a').bind('click', function(e){
      var path = $(this).getPath();
      var ahash={
                   'path':path
                };
      if (getFrameElement())
         window.parent.document.Aaddevent(e, ahash);
});

点击事件中的“路径”给出了被点击的标签的路径(例如html > body > div#bar > ul#abc.def.ghi > li#foo)。 getFrameElement() 返回被点击的帧。现在我想做的是使用这个路径并在其他 iframe 中触发点击事件

我已经定义了 sendevent 函数,另一个 iframe 从中获取父 iframe 的事件并触发与父 iframe 相同的事件并进行同步。

document.sendevent=function(e, ahash){
    var iframes= parent.document.getElementsByTagName('iframe');
    for (var i= iframes.length; i--;) {
        var iframe= iframes[i];
        if(iframe){
                    $(ahash.path).trigger('click');
                  }
    }
};

这就是我想要做的并使 iframe 工作的方式,遵循父 iframe 被点击元素的路径,然后触发 click 事件以使其他 iframe 使用该路径与父 iframe 同步

点击事件没有在 sendevent 函数内触发,但是当我在 sendevent 函数内执行 console.log(ahash .path) 时,我得到了父 iframe 点击元素的路径。我怎样才能使这种方法起作用或类似的东西。请建议我一些解决方案如何做到这一点。

【问题讨论】:

    标签: javascript jquery iframe click


    【解决方案1】:

    您无法使用$("a").trigger("click") 跟踪链接。您可以使用location.href = $("a").attr("href")。如果您只是想在两个框架中导航到相同的 url,请不要打扰 .getPath(),只需传递 href。在您的父页面中,使用它来绑定第一帧中的链接以同时导航第二帧:

    $("iframe:first").contents().find("a[href]").click(function() {
        $("iframe:last", top.document)[0].contentWindow.location.href = this.href;
    });
    

    编辑: 在 IE 和较新版本的 FireFox 和 Opera 中,您可以使用原生 DOM 方法 .click() 来模拟对链接的实际点击。 Chrome 尚不支持它,但可能最终会支持。要使用.getPath() 查找并单击链接,请在父页面中尝试:

    $("iframe:first").load(function() {
        $(this).contents().find("a[href]").click(function() {
            $("iframe:last", top.document).contents().find($(this.getPath())[0].click();
        });
    });
    

    【讨论】:

    • 是的,我想在两个框架中导航到相同的 url,我之前已经使它可行,但现在我有必要使用 .getPath() 并在其他框架中跟随父 iframe 的链接iframes 因为 href 是通过 jquery 设置的
    • 是否有可能如果我单击同一域中网页中的链接或选项卡,而不是更改 iframe 的 src,而是将单击元素的路径传递给另一个 iframe 以同步iframe?
    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 2011-07-03
    • 2018-11-04
    • 2016-06-22
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多