【问题标题】:Can javascript running inside an iframe affect the main page?在 iframe 中运行的 javascript 会影响主页吗?
【发布时间】:2009-06-04 17:25:16
【问题描述】:

部分代码:

下面的代码从我的数据库中提取一个查询,然后使用 inner.HTML = 在 div 中显示数据。它在原始用途中运行良好....

但是,在 iFrame 中调用以下版本,因为它用于更新页面。

页面没有错误,JavaScript 会触发,但最后一行不起作用...

我刚刚意识到,也许因为它是在隐藏的 iFrame 中加载,所以它试图在 iFrame 中设置 div 的 innerHTML,这当然不起作用。

这是怎么回事?这没有任何意义,因为我有另一个脚本以相同的方式在其末尾调用 JavaScript,并且它工作正常。

<?php
    while ($row = mysql_fetch_array($result))
    {
        $p = $p.'<div id="left"><img src="http://www.sharingizcaring.com/bleepV2/images/thumbs/'.$row[image].'" /></div>';
        $p = $p.'<div id="right"><h2>'.$row[artist].' - '.$row['title'].'</h2><br>'.$row['message'].'<br>';
        $p = $p.'<a href="http://www.sharingizcaring.com/bleepV2/'.$row[username].'">'.$row[username].'</a> '.$row[date].'</div>';
        $p = $p.'<div style="clear: both;"></div>';
        $p = $p.'<div id="dotted-line"></div>';
    }


    $p = addslashes($p);
?>

<script>

        alert('posts are firing? ');

        document.getElementById('posts').innerHTML = 'why doth this faileth?';
</script>

【问题讨论】:

    标签: javascript iframe


    【解决方案1】:

    你可以的! Read here for more info

    您可以通过从窗口元素设置和获取变量来影响包含 iframe 的文档:

    // normally you use...
    var whatever = "value";
    
    // use the window object instead, which is shared 
    // between the iframe and the parent
    window.whatever = "value";
    

    你应该知道的另一件事是你可以通过父对象访问主文档

    在 iframe 中你可以使用...

    parent.someattr;
    
    // or try this
    parent.getElementById('some_element');
    

    【讨论】:

    • 我才意识到父母。是我的问题的一部分。如何开窗? window.getElementById 之类的?
    • “窗口”。 part 只是一个更全局的范围,您可以将其用于变量。
    • 注意:我不推荐使用window,除非你必须...范围是一个美丽而有用的东西...如果一切都是全局的,那就没用了
    【解决方案2】:

    我想你想要的是:

    parent.getElementById('posts').innerHTML = 'why doth this faileth?';
    

    【讨论】:

    • + for '为什么这会失败?'
    • @IvanIvković 谢谢,但我只是复制了这个问题。 :)
    【解决方案3】:

    iframe 中的部分不被视为同一个文档。

    【讨论】:

      【解决方案4】:

      你必须使用父级。

      【讨论】:

        猜你喜欢
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-17
        • 2015-03-31
        • 2016-09-07
        • 1970-01-01
        相关资源
        最近更新 更多