如何从其子元素访问iframe元素 [英] How to access iframe element from its child element

查看:107
本文介绍了如何从其子元素访问iframe元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在事件处理程序函数中从其子元素访问iframe元素对象.

I have a requirement to access iframe element object from its child element in a event handler function.

一个例子就是这样.

function callback(ev) {
  //get the event target element
  var targetElement = ev.target;

  //get the document object of the target element
  var doc = targetElement.ownerDocument;

  //Question: how to get to the doc's iframe object
  // I tried these properties below, both returns null
  var ifrmEle = doc.parentElement;
  var ifrmEle = doc.parentNode;
}

假设在上面的示例中targetElement是body元素, 所以我的问题是如何访问拥有body元素的iframe元素?

Say the targetElement is the body element in the above example, So my question is how could I access the iframe element owning the body element?

感谢您的专业知识.

推荐答案

没有方便的属性可以为您提供该信息.

There's no convenient property that would give you that information.

最接近的做法是循环遍历父文档中的所有框架,直到找到包含同一文档的框架为止.

The closest you would do would be to loop over all the frames in the parent document until you found one containing the same document.

<!DOCTYPE html>
<meta charset="utf-8">
<title>Iframe Parent</title>
<h1>Iframe Parent</h1>
<iframe src="iframe.html" name="one"></iframe>
<iframe src="iframe.html" name="two"></iframe>
<iframe src="iframe.html" name="three"></iframe>
<iframe src="iframe.html" name="four"></iframe>

子文档

<!DOCTYPE html>
<meta charset="utf-8">
<title>Iframe</title>
<h1>Iframe</h1>
<p>This document is in a frame named <span>?</span>.</p>
<script>
    parent.document
    .querySelectorAll('iframe, frame')
    .forEach(frame => {
        if(frame.contentWindow.document === document) {
            document.querySelector('span').textContent = frame.name;
        }
    });
</script>

这篇关于如何从其子元素访问iframe元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆