dun*_*unc 5 javascript iframe jquery
由于我使用的小部件格式,我有一个页面,其中嵌入了多个 iframe。我不会粘贴代码,因为它庞大而笨拙,但它本质上就是这样:
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
<iframe>
<html>
<head></head>
<body>
blah
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
</iframe>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
但是,根据我使用的页面和模板,可能会有更多或更少的 iframe。
因此,我试图从最嵌入的 iframe 中获取此页面中所有 iframe 的 ID。
这可以用 jQuery 实现吗?我已经尝试了一些代码片段,但没有运气:
$('iframe', window.parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe', parent.document).each(function() {
console.log($(this).attr("id"));
});
$('iframe').each(function() {
console.log($(this).attr("id"));
});
Run Code Online (Sandbox Code Playgroud)
这些的输出是一个单一的 ID 字符串 - 不幸的是,它不是我想要控制的 iframe。
提前致谢,
编辑
如果未找到iframe所需的元素,则返回具有所需的id、 和 的元素。nullid
function searchIds(wantedId) {
var idArray = [], n,
search = function (iframes) {
var n;
for (n = 0; n < iframes.length; n++) {
if (iframes[n].frames.length > 0) {
search(iframes[n].frames);
}
idArray.push(iframes[n].frameElement.id);
idArray.push(iframes[n].frameElement);
}
};
search(window.top.frames);
for (n = 0; n < idArray.length; n += 2) {
if (idArray[n] === wantedId) {
return idArray[n + 1];
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
请注意,在主窗口被触发searchIds()之前不能运行。onload
| 归档时间: |
|
| 查看次数: |
4674 次 |
| 最近记录: |