gpt4 book ai didi

javascript - 访问同一域中的 iframe 内容

转载 作者:行者123 更新时间:2023-11-29 22:19:16 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的测试,以从其父容器修改 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 + "!");
}

首先.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 对象

关于javascript - 访问同一域中的 iframe 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13339543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com