我正在尝试创建一个简单的测试,以从其父容器修改 iframe 的内容,并从 iframe 修改父容器的内容。这是我到目前为止所拥有的:
第一个.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>
第二个.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 + "!");
}
第一个.js:
$(document).ready(function() {
var iframe = $("iframe");
modifyContent(iframe.contents(), "h1", "First");
});
第二个.js:
$(document).ready(function() {
if (!top.document)
return;
modifyContent(top.document.body, "h1", "Second");
});
为了运行代码,我使用 python -m SimpleHTTPServer 3000
并导航到 localhost:3000/first.html
。第一个 header 被修改并显示“Modified by Second!”但第二个标题只是说“第二”。我在这里缺少什么?
最佳答案
尝试在 iframe 完全加载后更改 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 对象
关于javascript - 访问同一域上的 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13339543/