要获取iframe内的按钮,这可能有效:
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
显然,您可以使用iframeDocument导航以获得所需内容,并使用您似乎知道的.innerHTML.如果iframe指向其父级以外的域,则无法获取iframe的内容.
更新:
您需要使用代码在准备好后获取框架的文档及其内容,因此您应该使用以下内容:
window.onload = function () {
var greeting = "hola, ";
var div1 = document.createElement("div");
var frame1 = document.createElement("iframe");
frame1.id = "frame1";
frame1.onload = function () {
alert("loaded");
var iframe = document.getElementById("frame1");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var button = iframeDocument.getElementById("mybutton");
if (button == null) {
alert("button is null");
}
};
frame1.src = "http://onemoredemo.appspot.com";
div1.appendChild(frame1);
document.body.appendChild(div1);
};
重要的是如何创建元素并将其附加到DOM – 而不仅仅是使用innerHTML. iframe的onload方法是为了保证它已准备就绪.实际的操作代码在jsFiddle中不起作用,因为跨域问题,但是你应该需要的.