从父标签中通过 id 获取元素
get element by id from parent tag
我的DOM如下。
<html><head>...</head><body><script>...</script>
<iframe id="frame">
#document
<html>...</html> <!-- 2 -->
</iframe>
</body>
</html>
我在 iframe
中绑定了部分内容(即 html 2)。在 html_2 部分中,我调用 document.ready
使用 getElementById
获取 iframe
的 id
,但我得到 null
。如何获取iframe
?
的id等属性值
$("iframe").each(function() {
alert($(this).attr("id"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>...</head>
<body>
<script>
...
</script>
<iframe id="frame">
</iframe>
<iframe id="frame1">
</iframe>
<iframe id="frame2">
</iframe>
</body>
</html>
- 使用
.attr("id")
- 对于多个 iframe,使用
.each()
遍历所有 iframe
- 使用它来获取当前的 iframe
试试这个:
document.getElementById("frame").contentWindow.document.getElementById("div1")
我按照下面的方式做了,
$("#iframe", parent.document).attr("id");
顺便说一句,感谢所有回答和帮助我提出宝贵意见的人。
我的DOM如下。
<html><head>...</head><body><script>...</script>
<iframe id="frame">
#document
<html>...</html> <!-- 2 -->
</iframe>
</body>
</html>
我在 iframe
中绑定了部分内容(即 html 2)。在 html_2 部分中,我调用 document.ready
使用 getElementById
获取 iframe
的 id
,但我得到 null
。如何获取iframe
?
$("iframe").each(function() {
alert($(this).attr("id"));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>...</head>
<body>
<script>
...
</script>
<iframe id="frame">
</iframe>
<iframe id="frame1">
</iframe>
<iframe id="frame2">
</iframe>
</body>
</html>
- 使用
.attr("id")
- 对于多个 iframe,使用
.each()
遍历所有 iframe - 使用它来获取当前的 iframe
试试这个:
document.getElementById("frame").contentWindow.document.getElementById("div1")
我按照下面的方式做了,
$("#iframe", parent.document).attr("id");
顺便说一句,感谢所有回答和帮助我提出宝贵意见的人。