Frame is used to store subpages, which can be either iframe or frameset. The window object is a global object, and all functions and objects on the page are within its scope.
1. Parent represents the parent window. If the parent window has several levels of nesting, top represents the top-level parent window.
self represents the window itself.
if(self==top){//}判断窗口是否处于顶级 if(self==parent){}//也可以
2.1. The parent page accesses the child page elements. The idea is that the elements of the subpage are all in its window.document object. It is easy to get it first and then talk about it.
It is best to set the name attribute of the frame, which is the most convenient operation. Such as
<iframe name="test" src="child.html"></iframe>
If you want to get the element with the id 'menu' in child.html, you can write like this:
window.frames["test"].document.getElementById('menu'); //由于所有的函数都存放在window对象里面,可去掉开头的window: frames["test"].document.getElementById('menu'); //在浏览器中,帧的name属性被默认等同于子页面的window对象,因此可以进一步简写: test.document.getElementById('menu');
2.2 The parent page accesses child page functions or objects. The functions and objects of the subpage are all in its window object. Same as above. The key is to obtain the object.
//假如child.html定义了showMesg函数,需要在父中调用,则这样写 window.frames['test'].showMesg(); //简写形式 test.showMesg(); //同理,对象也是如此访问 alert(test.person);
2.3 Other ways to obtain documents.
First use 'document.getElementById()' or 'document.getElementsByTagName()' to get the frame as an Element under the document, and then access its properties contentDocument/contentWindow (specific to iframe and frame). The first one is not supported by ie7-. The second chrome is not supported.
<iframe id="testId" src="child.html"></iframe> //====== var doc=document.getElementById('testId'); //或者 var doc=document.getElementsByTagName('iframe')[0]; 然后 var winOrdoc=doc.contentDocument||doc.contentWindow;//二选一 if(winOrdoc.document)winOrdoc=winOrdoc.document; winOrdoc.getElementById('menu'); //如果需要window对象,则这样写: if(winOrdoc.defaultView)winOrdoc=winOrdoc.defaultView;
3.1 Sub-page accesses parent page elements. The idea is the same as 2.1, first get the parent window window.document object
parent.window.document.getElementById('parentMenu'); //简写 parent.document.getElementById('parentMenu');
3.2, The child page accesses the parent page function or object. The idea is the same as 2.2, first get the parent window window object.
parent.parentFunction();
Finally, let me mention the same-origin policy of js, that is, the js code located on website A is not allowed to access the content located on website B, even if the code originates from website B. If the frame is a page from another website, then when accessing each other according to the above method, the browser should prompt: 'No permission' error.