【问题标题】:Add target=“_top” to ink that is inside the fancybox iframe将 target=“_top” 添加到 fancybox iframe 内的墨迹
【发布时间】:2014-05-27 19:48:37
【问题描述】:

我有一个通过fancybox iframe 访问的页面设置。 fancybox iframe 中的链接如何加载到 iframe 的父窗口中?所以如果用户点击链接,它会重新加载页面并加载点击的链接。如何为所有链接添加 target="_top" 属性?

例如

$("iframe").on("load", function () {
    $("a").each(function() {
      $(this).attr('target', '_top');
   });
}) 

【问题讨论】:

    标签: javascript jquery iframe fancybox fancybox-2


    【解决方案1】:

    假设在您的子页面中有常规链接,例如:

    <p>This link opens <a href="http://google.com">GOOGLE</a></p>
    <p>This link opens <a href="http://jsfiddle.net">JSFIDDLE</a></p>
    <p>This link opens <a href="http://stackoverflow.com">STACKOVERFLOW</a></p>
    

    您可以使用fancybox afterShow 回调将属性 onclick 设置为父页面中的每个链接。然后,将parent.location.assign()$.fancybox.close() 设置为onclick 属性值。

    这是您父页面的代码:

    jQuery(document).ready(function ($) {
        $(".fancybox").fancybox({
            type : "iframe",
            afterShow : function () {
                $(".fancybox-iframe").contents().find("a").attr("onclick", "parent.location.assign(this.href);parent.$.fancybox.close();")
            }
        });
    }); // ready
    

    现在,iframe 页面上的每个链接都会关闭 fancybox 并在父(顶部)页面中加载引用的 URL。

    注意事项

    • 我们需要在.assign()方法中传递this.href,对应每个链接的href值。
    • 我们不需要在子页面中包含 jQuery。
    • 使用 iframe 需要遵守 Same-origin policy

    查看演示:http://www.picssel.com/playground/jquery/openURLfromChildPage_13apr14.html

    【讨论】:

    • 感谢您的回复。如何不将此代码用于我的课程(.ajax-processed)
    • @zhe:什么意思?如果您对不同类型的内容使用相同的 fancybox 代码,您可以设置一个条件以将代码仅应用于 iframe。这就是你想要的吗?
    • 对不起,我不懂英语。我用谷歌翻译。我需要打开父(顶部)页面中的所有链接。您的代码确实有效。但有些链接在 iframe screenshot 中打开
    • @zhe 好吧,在你的问题中添加这些链接的相关 html/js 代码,否则我猜不出你在做什么。
    【解决方案2】:

    如果您使用的是 Fancybox 3,您将需要这个稍作改动的版本:

    jQuery(document).ready(function ($) {
        $("[data-fancybox]").fancybox({
            type : "iframe",
            onComplete : function () {
                $(".fancybox-iframe").contents().find("a").attr("onclick", "parent.location.assign(this.href);parent.$.fancybox.close();")
            }
        });
    });
    

    添加这个额外的答案,因为这个线程是搜索中唯一几乎有用的东西。我觉得 Fancybox 的当前版本值得更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2020-03-11
      • 2011-02-28
      相关资源
      最近更新 更多