简体   繁体   English

如何使用 Javascript 访问 iframe 元素?

[英]How can I access iframe elements with Javascript?

I have a webpage where there is a textarea within a iframe.我有一个网页,其中 iframe 中有一个文本区域。 I need to read the value of this textarea from its child page JavaScript.我需要从它的子页面 JavaScript 中读取这个 textarea 的值。 Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.目前通过在 JavaScript 中使用window.parent.getelementbyID().value ,我能够获取父页面中除 iframe 中的 textarea 之外的所有控件的值。

The frame id and frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference.我的父页面中的框架 id 和框架名称在运行时会发生变化,因此我们不能使用框架 id/框架名称作为参考。

If you have the HTML如果你有 HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript和 JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src. inside现在是对文档的引用,因此您可以执行getElementsByTagName('textarea')和任何您喜欢的操作,具体取决于 iframe src 中的内容。

Using jQuery you can use contents() .使用 jQuery,您可以使用contents() For example:例如:

var inside = $('#one').contents();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM