Why is 'self' what it is?
I have a frame page....
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Main title</title>
<script type="text/javascript" src="JS.js"></script>
</head>
<frameset rows="10%,90%" id="frameid" name="frameName">
<frame src="FrameA.htm" name="F_A">
<frame src="FrameB.htm" name="F_B">
</frameset>
</html>
Here's FrameA.htm; FrameB looks similar
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>
<script type="text/javascript" src="JS.js"></script>
<title>Frame A Title</title>
</head>
<body onload="parent.ldfunc()" class="Resize" id="idA">
Body of frame A
</body>
</html>
and finally a javascript JS.js
function ldfunc () {
alert("window.self.name: " + window.self.name);
alert("window.self.document.body.id: " + window.self.document.body.id);
}
Now here's the rub...
1) If the onload clause in the body tag is parent.ldfunc() as it is above, 'self' seems to be the frame page, not page A or page B. I.e. Id is displayed 开发者_开发百科as frameid.
2) If the onload clause is ldfunc() WITHOUT the parent, 'self' points at page A or page B as expected. I.e. id is displayed as idA or iadB.
In other words, self seems to follow the function location, not the page.
Why did I try this? I'm going to have several thousand pages that will be loaded in B by A and I thought I could eliminate the need to put the script in each of their headers.
Is there some way to make the script loaded by the frame page global and available to the other pages?
window inside that function is not dynamically referenced. The reference to window is created on the moment the function is declared and is thus always the window reference to where the function resides. This is called a closure, when you basically embed external references inside a function at declare time.
You need to pass the context window as an argument upon calling the function.
Put scripts inside the top frame/window. Call functions with:
top.funcName();
And pass context.
top.funcName(window);
精彩评论