这听起来像是一个简单的任务,但我发现解决方案奇怪地难以确定。
我想要做的就是使用 iframe 内的按钮单击,使用 iframe 中的数据填充父窗口中的文本输入框。是的,两个页面都在同一个域中。
使用原始 JS、Jquery、Ajax 等尝试了各种解决方案,但没有任何乐趣。我找到了填充 <div>
的解决方案容器,但将相同的目标 ID 应用于文本输入不起作用。
我还成功地从父页面使用此 Jquery 脚本将数据发送到 iframe,但无法弄清楚如何执行相反的操作(iframe 到父页面)
<script>
$(document).ready(function(){
$('#submit').click(function(){
var iframe = document.getElementById('myiframe');
var doc = iframe.contentDocument || iframe.contentWindow.document;
var elem = document.getElementById('source');
doc.getElementsByName('target')[0].value = elem.value;
});
});
</script>
简化的设置。
父级.html:
<!DOCTYPE html>
<html>
<body>
<iframe id="myiframe" frameborder="1" src="child.html"></iframe>
<form>
Iframe data populates here: <input type="text" name="target" id="target">
</form>
</body>
</html>
child.html:
<!DOCTYPE html>
<html>
<body>
<form>
Iframe data is input here: <input type="text" name="source" id="source">
<button type="button" onclick="functionToSendSourceToParent();">
</form>
</body>
</html>
最佳答案
是不是很简单?在本地(Chrome 除外)上的工作方式如下:
父级.html:
<!DOCTYPE html>
<html>
<body>
<iframe id="myiframe" frameborder="1" src="child.html"></iframe>
<form>
Iframe data populates here: <input type="text" name="target" id="target">
</form>
</body>
</html>
child.html
<!DOCTYPE html>
<html>
<script>
function functionToSendSourceToParent() {
var inp = document.getElementsByName("source")[0].value;
parent.document.getElementsByName("target")[0].value = inp;
}
</script>
<body>
<form>
Iframe data is input here: <input type="text" name="source" id="source">
<button type="button" onclick="functionToSendSourceToParent();">Send2Parent</button>
</form>
</body>
</html>
Chrome 控制台报告:
child.html:6 Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.<br/>
at functionToSendSourceToParent (file:///X:/child.html:6:12)<br/>
at HTMLButtonElement.onclick (file:///X:/child.html:13:65)<br/>
关于javascript - 如何通过 iframe 按钮提交填充父页面内的文本输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57650791/