我已经尝试了很多,但是每次遇到此错误时:“ Uncaught TypeError:content.getElementById不是函数”(附加脚本)
帮助将不胜感激:D花了我几个小时,无法弄清楚
var newcode = "";
var oldcode = "";
function update(){
var iframe = document.getElementById('if');
var content = iframe.contentWindow.document.getElementsByTagName('html')[0].getElementsByTagName('body')[0];
newcode = content.getElementById("code").innerHTML;
if(newcode != oldcode){
oldcode = newcode;
alert("lol"+newcode+"lol");
document.head.innerHTML += "<script>"+newcode;
}
}
window.setInterval(function(){
update();
}, 5000);
<html>
<head>
<title>Check</title>
</head>
<body>
<iframe id="if" src="myurl"></iframe>
</body>
</html>
getElementById
只能在上调用document
-不能在上调用HTMLElement
(甚至不能在上调用HTMLBodyElement
)。毕竟,ID在文档中应该是唯一的。改成
var newCode = iframe.contentWindow.document.getElementById('code').innerHTML;
因此这iframe.contentWindow.document
是指iframe中的文档。
如果您只想从祖先节点中选择一个特定的ID而无需返回文档,则可以使用querySelector
-仅在ID前面加上前缀#
:
var newcode = content.querySelector("#code").innerHTML;
(但是content
,假设HTML有效,则无需首先导航到)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句