我有几个页面(全部位于与母版页相同的目录中),它们通过 iFrame 加载到父级中。我想获取每个子页面标题并将它们加载到一个数组中。那可能吗?
到目前为止,我能做的最好的事情就是在页面加载到 iFrame 时从子页面传递图 block ,但我需要从一开始就预加载所有标题,以便填充目录,如下所示:
父代码:
var pages = new Array("page1.html", "page2.html", "page3.html");
var maxPages = pages.length;
function pageTitle(title){ //called from inside a child HTML
document.getElementById("titleText").innerHTML = title;
};
子代码:
window.onload = function passTitle(){
var title = $(document).find("title").text();
parent.pageTitle(title);
};
最佳答案
您想要使用window.frames
- 这是框架对象的列表(不是数组 - 对于第二个解决方案很重要)
那么,最简单的方法就是这样
var pageTitles = [];
for (i = 0; i < window.frames.length; i++) {
if( !!window.frames[i].document) { // only frames in same domain
pageTitles.push(window.frames[i].document.title);
}
}
或者,更先进一点,但在我看来更好的方式
var pageTitles = [].filter.call(window.frames, function(frame) {
return !!frame.document; // return only frames in same domain
}).map(function(frame) {
return frame.document.title;
});
actually you could use just
window
without the.frames
- at least in firefox, becausewindow.frames === window
- however, I'd recommend usingwindow.frames
for clarity in code
关于javascript - 我可以使用 JavaScript 获取我的域中的外部页面的标题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35518383/