javascript - 在 iframe 中运行的 javascript 会影响主页吗?

标签 javascript iframe

部分代码:

我下面的代码从我的数据库中提取查询,然后使用 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>

最佳答案

你可以的! 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');

关于javascript - 在 iframe 中运行的 javascript 会影响主页吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/951946/

相关文章:

javascript - Facebook 喜欢 JavaScript 添加时不工作

javascript - Billboard.js 可选的 Y 网格线 - 标签背景的样式

javascript - 尝试使用 d3.csv 时出现错误 "data not defined"?

jquery - &lt;textarea&gt; 上的 Kendo 编辑器创建 iframe,因此无法在其中绑定(bind)任何 javascript 事件

javascript - 让 iframe 在网页上对齐

javascript - iframe.scrollTo() 不适用于 iPad 上的 Excel/PowerPoint 文档

javascript - 添加类后获取元素文本值

javascript - 如果我的网站通过 iframe 打开第 3 方网站,第 3 方网站能否成功设置自己的 cookie?

javascript - 从 iframe 检索 PDF

javascript - 我需要使用 javascript 将 "flat"json 对象转换为具有一对多匹配能力的嵌套 json 树