親コンテナーから 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>
共有.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
ます。最初のヘッダーが変更され、「Modified by Second!」と表示されます。しかし、2 番目のヘッダーには「Second」とだけ表示されます。ここで何が欠けていますか?