很简单html
我不知道为什么不起作用的代码!
html
文件包含在带有 id 的 iframe 标记中。
脚本创建一个元素并尝试将其附加到 iframe
.
它不起作用,我不知道它为什么起作用(参见注释的代码)!
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<iframe id="s1" src="ifsrc.html"></iframe>
<script>
var soal = document.createElement("a");
var soaltext = document.createTextNode("text");
var soalat = document.createAttribute("class");
soalat.value = "class ";
var soalid = document.createAttribute("id");
soalid.value = "attid";
soal.setAttributeNode(soalat);
soal.setAttributeNode(soalid);
soal.appendChild(soaltext);
//document.body.appendChild(soal); its work!
var iFrame = document.getElementById("s1");
var iFrameBody;
iFrameBody = iFrame.contentDocument.getElementsByTagName("body")[0];
iFrameBody.appendChild(soal); // its not work!
</script>
</body>
</html>
ifsrc.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
sample text
</body>
</html>
最佳答案
它的工作!
<script>
var soal = document.createElement("a");
var soaltext = document.createTextNode("tgggext");
soal.appendChild(soaltext);
alert("ad");
var iFrame = document.getElementById("s1");
var iFrameBody;
iFrameBody = iFrame.contentDocument.getElementsByTagName("body")[0];
iFrameBody.appendChild(soal);
</script>
但是它不起作用!!!
<script>
var soal = document.createElement("a");
var soaltext = document.createTextNode("tgggext");
soal.appendChild(soaltext);
var iFrame = document.getElementById("s1");
var iFrameBody;
iFrameBody = iFrame.contentDocument.getElementsByTagName("body")[0];
iFrameBody.appendChild(soal);
</script>
终于我找到了我的问题。它是关于就绪事件的。
警报几乎不需要时间,足以让 iframe 完成加载并准备就绪。
我使用这段代码而不是上面的代码。
$(document).ready(function(){
$('#s1').ready(function(){
$('#s1').contents().find('body').html("<a>Hey, i`ve changed conten!</a>");
});
});
它工作正常,因为就绪事件等待 iframe 加载完成。
关于javascript - 在 iframe 中创建 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25195439/