如何从iframe内部关闭iframe?

10

我有一个WordPress网站,其中的文章被加载到一个iframe中。

这是有效的代码:

<a class="trick" rel="<?php the_permalink() ?>" href="<?php the_permalink() ?>"><?php the_title(); ?></a>
$(document).ready(function(){
    $.ajaxSetup({cache:false});
    $(".trick").click(function(){
        var post_link = $(this).attr("rel");
        $("#frame").css("display","block");
        $("#frame").attr("url", post_link);
        $("body").css("overflow","hidden");
    });

  });         </script>
<iframe id="frame" frameborder="no" allowtransparency="true" width="100%" height="100%" scrolling="no" src=""></iframe>

现在问题是如何从iframe内部关闭加载的iframe?

主页面是index.php(WordPress的主循环),iframe的内容是single.php(单个文章),不包含页眉和页脚。

谢谢。


以下是我在single.php中得到的内容:

<head>

<script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
    $(document).ready(function(){
        $("#close").click(function(){
            $('#frame', window.parent.document).remove();

             });

        });

    </script>


</head> 

<body>
<div id="container-single">
    <button id="close" >Close</button>



    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

        <article <?php post_class('single') ?> id="post-<?php the_ID(); ?>">

            <h1 class="entry-title"><?php the_title(); ?></h1>

            <div class="entry-content">

                <?php the_content(); ?>

                <?php wp_link_pages(array('before' => 'Pages: ', 'next_or_number' => 'number')); ?>

                <?php the_tags( 'Tags: ', ', ', ''); ?>

                <?php include (TEMPLATEPATH . '/_/inc/meta.php' ); ?>

            </div>


        </article>



    <?php endwhile; endif; ?>

    </div>

</body>

1
关闭 iframe?你是什么意思?你想要移除内部的 iframe 还是怎样? - Reza Owliaei
可能是重复的问题:如何在iframe内部关闭iframe - Oleg V. Volkov
4个回答

20

single.php 中执行以下代码,该文件被加载到 iframe 内。这将使用父级 window 作为上下文查找并移除或隐藏 iframe

//You can call hide() if you want to just hide it
$('#iframe', window.parent.document).remove();

我尝试过这个但是不起作用,你可以在我的问题中看到我编辑过的single.php内容... - Luca Frank Guarini
只是确认一下。iframe 是否在同一个域中? - ShankarSangoli
是的,当然。iframe加载了一个WordPress文章。 - Luca Frank Guarini
然后它应该找到iframe并关闭它。你能console.log并查看$('#iframe', window.parent.document)返回什么吗? - ShankarSangoli
搞定了。谢谢。 - Felipe Alameda A
显示剩余2条评论

9

其实我知道一个小技巧。

在父页面上创建一个函数。

var closeIFrame = function() {
     $('#iframeid').remove();
}

在任何地方调用要关闭的iframe。
parent.closeIFrame();

有些棘手,不是吗?


1
如果您像这样声明一个函数,它不会被添加到window对象中,我认为您需要这样做:var closeIFrame = function () { ... } - Jasper
我发现这个答案很有用。这就是我寻找了几个小时的解决方案。 - Sohel Pathan

1
// Inside the iframe    
frameElement.remove();

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接