使用javascript/html控制iframe内容

使用javascript/html控制iframe内容,javascript,html,Javascript,Html,在我的网页中,我有这样一个iframe: <iframe src="thispage.html" width="100%" height="600" frameBorder="2"></iframe> (iframe是同一站点上的一个页面…) 我的问题是,是否可以在具有iframe的页面上使用javascript来控制“thispage.html”(如使用javascript函数?是的,例如,如果您给iframe一个ID <iframe src="thispa

在我的网页中,我有这样一个iframe:

<iframe src="thispage.html" width="100%" height="600" frameBorder="2"></iframe>

(iframe是同一站点上的一个页面…)


我的问题是,是否可以在具有iframe的页面上使用javascript来控制“thispage.html”(如使用javascript函数?

是的,例如,如果您给iframe一个ID

<iframe src="thispage.html" width="100%" height="600" frameBorder="2" id="MyIframe"></iframe>
因此,您可以调用它的函数,例如

iw.theFunctionInsideIframe();
您可以定位DOM元素,如

var anElement = iw.document.getElmentByID("myDiv");

是的,你可以。假设您的
iframe
的ID是
'myIFrame'


然后,在JavaScript中添加以下内容:

//获取iframe
常量iFrame=document.getElementById('myIFrame');
//假设您想访问ID为“myButton”的按钮,
//您可以通过以下代码访问:
const buttonInIFrame=iFrame.contentWindow.document.getElementById('myButton');
//如果需要调用iframe中的函数,可以按如下方式调用它:
iFrame.contentWindow.yourFunction();

希望有帮助:)

thispage.html是主html文件或加载到iframe的文件。
var anElement = iw.document.getElmentByID("myDiv");