将输入从父文档传递到iframe

时间:2015-01-04 16:38:36

标签: javascript jquery html5 dom iframe

我的项目主页上嵌入了iframe,其src已更改为具有相同输入ID (id="name1")的不同HTML模板,这些来源为" first.html&#34 ;和" second.html"并且托管在同一台服务器上(不应该有任何同源问题)。

first.html的代码是:

<p>A common computer greeting is: <input type="text" name="display" id="name1"/></p>

second.html的代码是:

<p>People frequently use the phase: <input type="text" name="display" id="name1"/></p>

我已经在jsfiddle上传了示例代码(当src约为:空白时,此代码有效,我只是直接写入iframe):http://jsfiddle.net/EdwardMoseley/x6gqk7qb/

Field1: <input type="text" id="field1" value="Hello World!"><br>
<iframe src="about:blank" name="myFrame"></iframe>
<button type="button" onclick="writeToFrame();">Try it!</button>
<script>
function writeToFrame() {
var iframe = window.frames["myFrame"].document;
iframe.open();
iframe.write(document.getElementById("field1").value);
iframe.close();
}
</script>

我尝试使用以下代码使其适应我的情况:

function writeToFrame() {
var iframe = window.frames["myFrame"].document;
iframe.open();
iframe.write(iframe.getElementById("name1").value = document.getElementById("field1").value);
iframe.close();
}

不幸的是,当我点击按钮调用该功能时,iframe就会消失。

有什么想法吗?如果您有任何疑问或想要澄清,请告诉我。

感谢您的投入!

0 个答案:

没有答案