Add target=“_top” to ink that is inside the fancyb

2019-09-01 04:58发布

I have a page setup that is accessed through a fancybox iframe. How can a link that is inside the fancybox iframe, load in the parent window of the iframe? So if the user clicks the link, it will reload the page and load the clicked link. How do I add a target="_top" attribute to the all links?

e.g.

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

2条回答
我想做一个坏孩纸
2楼-- · 2019-09-01 05:18

If you are using Fancybox 3, you will want this slightly altered version:

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();")
        }
    });
});

Adding this extra answer as this thread is about the only near useful thing that shows up in searches. I felt it was worth updating for the current version of Fancybox.

查看更多
贪生不怕死
3楼-- · 2019-09-01 05:25

Assuming that in your child page you have regular links like :

<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>

You could set the attribute onclick to each link from within the parent page using the fancybox afterShow callback. Then, set parent.location.assign() and $.fancybox.close() as the onclick attribute value.

This is the code for your parent page :

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

Now, each link on the iframed page will close fancybox and load the referred URL in the parent (top) page.

NOTES :

  • We need to pass this.href within the .assign() method, which corresponds to href value of each link.
  • We don't need to include jQuery in the child page.
  • Working with iframes is subject to the Same-origin policy

See demo : http://www.picssel.com/playground/jquery/openURLfromChildPage_13apr14.html

查看更多
登录 后发表回答