如何使用 Javascript 访问 iframe 元素? [英] How can I access iframe elements with Javascript?
问题描述
我有一个网页,其中 iframe 中有一个 textarea.我需要从它的子页面 JavaScript 中读取这个 textarea 的值.目前通过在 JavaScript 中使用 window.parent.getelementbyID().value
,我能够获取父页面中除 iframe 中的 textarea 之外的所有控件的值.
I have a webpage where there is a textarea within a iframe. I need to read the value of this textarea from its child page JavaScript. 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.
我的父页面中的框架 ID 和框架名称在运行时会发生变化,因此我们无法使用框架 ID/框架名称作为参考.
The frame id and frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference.
推荐答案
如果你有 HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
和 JavaScript
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
现在是对文档的引用,因此您可以执行 getElementsByTagName('textarea')
和任何您喜欢的操作,具体取决于 iframe src 中的内容.
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.
这篇关于如何使用 Javascript 访问 iframe 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!