我有如下所列的父文档和 iframe 子文档:
parent.html
<div id="parent">
<iframe src="child.html"></iframe>
</div>
<div><!-- the UL List getting from child.html will be displayed here--></div>
child.html
<div id="child_element_1"></div>
<div id="child_element_2">
<div id="child_element_2_1"></div>
<div id="child_element_2_2"></div>
</div>
<div id="child_element_3">
<div id="child_element_3_1"></div>
</div>
我想要的是一个 UL 列表,它具有 child.html 中每个 div id 的层次结构。 (见下图)
在那之后,我想把 UL 放在 parent.html 的某个地方 非常感谢您的提前支持。欢迎使用 Jquery 或 JavaScript。
最佳答案
以下假设 iFrame 在同一域中,否则您没有脚本访问权限。
/* page load code*/
$(function(){
$('#iframeID').on('load',function(){
iframeToList( $(this).contents().find('body'))
});
});
function divToList( $root){
var html=['<ul>'];
$root.children('div[id]').each( function(){
html.push('<li>'+this.id);
var $children=$(this).children('div[id]')
if( $children.length){
html.push( divToList( $(this)))
}
html.push('</li>')
})
html.push('</ul>')
return html.join('');
}
function iframeToList( $root){
$('body').append( divToList($root));
}
演示:
由于 Chrome 中的错误,如果没有动态创建的 iframe 的 src
,我无法触发 load
,因此有浏览器相关的演示:
http://jsfiddle.net/efzCu/2 - 适用于 Firefox
http://jsfiddle.net/efzCu/3 - 适用于 Chrome
具有真实 src
的实时页面不需要依赖于浏览器的代码
关于javascript - 获取 iFrame DOM 子页面中的每个 div id,然后从 Parent 中的这些 id 生成 UL 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14788486/