简体   繁体   English

JS功能在窗口中不起作用

[英]JS function doesn't work in a window

I open a new window and I need to call a function on it. 我打开一个新窗口,需要在其上调用一个函数。 If I write in the new window the funcion inside $(document).ready it works, but I would like to call it as a "normal" function... My code: 如果我在新窗口中编写$(document).ready内的函数,它可以工作,但是我想将其称为“正常”函数...我的代码:

var mywindow = window.open('', '', 'height=600,width=800');
mywindow.document.write('<html><head><title>My Title</title>');
mywindow.document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>');    
mywindow.document.write('<script type="text/javascript" src="function.js"></script>');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.document.close();   
mywindow.myFunction();   

I get "mywindow.myFunction is not a function" 我得到“ mywindow.myFunction不是函数”

Writing the function on works... 在作品上写函数...

mywindow.document.write('<script> $(document).ready(myFunction())</script>')

why? 为什么? What's wrong when I call the function? 调用该函数有什么问题?

var mywindow = window.open('', '', 'height=600,width=800');
mywindow.document.write('<html><head><title>My Title</title>');
mywindow.document.write('<script type="text/javascript" src="full host and path to js"></script>'); // see 1.
mywindow.document.write('</head><body >');
mywindow.document.write('</body></html>');
mywindow.document.close();  

mywindow.addEventListener('load', function() { // see 2.
    mywindow.myFunction();
});
  1. the src for javascript needs to be fully qualified - eg http://example.com/path/file.js javascript的src需要完全合格-例如http://example.com/path/file.js
  2. you must mywindow.document.close(); 您必须mywindow.document.close(); to trigger the load event, then and only then will the function be available 触发加载事件,然后只有此功能才可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM