目前我有两个 HTML 文件。一个名为index.html,另一个名为editor.html
在index.html里面我有一个editor.html的iframe,这个iframe上面也是我做的一个通知系统。要运行通知,它使用我创建的函数,可以像这样使用:
Notification("msg");
当我从index.html内部调用该函数时,它效果很好,因为该函数修改了index.html的html代码(通过.innerHTML)。当我尝试从 editor.html 调用它时出现问题
即使将 editor.html 添加到 index.html 中,就像在 index.html 顶部一样:
<script src="editor.html"></script>
我在 editor.html 中写了这个:
<script src="index.html"></script>
当我尝试从 editor.html 运行通知函数时,出现错误,因为该函数位于index.html 内部并修改index.html,而不是 editor.html。
请记住,在每个 index.html 和 editor.html 中,javascript 都位于标记中,因为文件中还有其他 html。谢谢,如果您需要进一步确认,请提问。
最佳答案
如果 iframe 和容器位于同一域中,则效果很好。
您可以将通知函数的定义放在单个外部文件中,例如 main.js:
function Notification( msg )
{
var div = document.getElementById("notification-div") ;
div.innerHTML = msg ;
/* The important thing is make this to be the container window when
* Notification is called, so document is the desired one.
*/
}
在index.html 中,您应该有 iframe 和 div 来打印通知文本:
<div id="notification-div"></div>
<iframe src="editor.html" width=300 height=200></iframe>
然后在index.html中包含main.js:
<script type="text/javascript" src="main.js"></script>
在index.html中可以直接调用,只要这是window即可:
Notification( "From index.html" ) ;
/* window will be this in the Notification function, so the call to
* document.getElementById, will actually be window.document.getElementById
*/
在 editor.html 中,您可以将容器窗口对象引用为 top。所以这个调用将给出期望的结果:
top.Notification( "From editor.html" ) ;
/* top will be this in the Notification function, so the call to
* document.getElementById, will actually be top.document.getElementById
*/
关于javascript - 在 script 标签内的不同 HTML 文件中运行 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38649158/