【发布时间】:2012-10-31 15:07:57
【问题描述】:
我正在尝试创建一个简单的测试来从其父容器修改 iframe 的内容,并从 iframe 修改父容器的内容。到目前为止,这是我所拥有的:
first.html:
<!doctype html>
<html>
<head>
<title>First</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="shared.js"></script>
<script type="text/javascript" src="first.js"></script>
</head>
<body>
<h1>First</h1>
<iframe src="http://localhost:3000/second.html"></iframe>
</body>
</html>
second.html:
<!doctype html>
<html>
<head>
<title>Second</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="shared.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>
<body>
<h1>Second</h1>
</body>
</html>
shared.js:
function modifyContent(targetContainerElement, targetSelector, sourceString) {
$(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}
first.js:
$(document).ready(function() {
var iframe = $("iframe");
modifyContent(iframe.contents(), "h1", "First");
});
second.js:
$(document).ready(function() {
if (!top.document)
return;
modifyContent(top.document.body, "h1", "Second");
});
要运行代码,我使用python -m SimpleHTTPServer 3000 并导航到localhost:3000/first.html。第一个标题被修改并显示“第二个修改!”但第二个标题只是说“第二”。我在这里错过了什么?
【问题讨论】:
标签: javascript iframe cross-domain