我正在尝试创建一个简单的测试,以从其父容器中修改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
。第一个标题已修改,并说"第二个修改!"但是第二个标题只是说"第二个"。我在这里缺少什么?
在完全加载时尝试更改iframe内部的H1标签:
$(document).ready(function() {
var iframe = $("iframe");
iframe.load(function ()
{
modifyContent(iframe.contents(), "h1", "First");
});
});
加上我认为您应该重写modifyContent
:
function modifyContent(isJquery, targetContainerElement, targetSelector, sourceString)
{
if ( isJquery )
targetContainerElement.find(targetSelector).html("Modified by " + sourceString + "!");
else
$(targetContainerElement).find(targetSelector).html("Modified by " + sourceString + "!");
}
只有 targetContainerElement
会起作用,因为您实际上不需要将其包装在$()中,因为它已经是jQuery对象