基于对 this question 的回答,我试图将元素直接附加到没有 src
属性的空 iframe
中。
但是,iframe
上的 appendChild
似乎无提示地失败了。
在下面的代码中,doc.write("Hello World");
工作正常,但是 myform2.appendChild(input2);
没有改变 框架的 innerHTML
,也不会抛出错误。
<html>
<body>
<iframe name = "myframe" id = "myiframe">
</iframe>
<script>
var myform2 = document.createElement("form");
var input2 = document.createElement("input");
input2.name = "quantity";
input2.value = "10";
myform2.appendChild(input2);
</script>
<script>
var getFrame = document.getElementById('myiframe');
var doc = getFrame.contentDocument || getFrame.contentWindow.document;
// doc.write("Hello World");
doc.body.appendChild(myform2); // Does not work.
</script>
</body>
</html>
使用原始 Javascript 将表单添加到 iframe
的正确方法是什么?
我正在寻找非 jQuery 解决方案,因为我想了解魔法是如何运作的,而不是让 jQuery 施展魔法。
最佳答案
我认为这是一个时间问题。加载文档后尝试运行脚本:
<body onload="loadMe();">
<iframe name = "myframe" id = "myiframe">
</iframe>
<script>
function loadMe() {
var myform2 = document.createElement("form");
var input2 = document.createElement("input");
input2.name = "quantity";
input2.value = "10";
myform2.appendChild(input2);
var getFrame = document.getElementById('myiframe');
var doc = getFrame.contentDocument || getFrame.contentWindow.document;
doc.body.appendChild(myform2); // Does not work.
}
</script>
</body>
关于javascript - 如何将表单写入空的 iframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23528798/