简体   繁体   English

有没有办法从外部文件调用 onload 内部定义的函数

[英]Is there a way to call function defined inside onload from an external file

Following is a sample code created based on the scenario.以下是基于场景创建的示例代码。 showData() function is defined inside a javascript load function. showData() 函数是在 javascript 加载函数中定义的。 I wanted to call showData() from another file maybe on a button click.我想通过单击按钮从另一个文件中调用 showData()。 I know this will work if the showData is made global.我知道如果 showData 是全局的,这会起作用。 It's not possible to make the function global, as in this scenario it's a dynamically generated code.无法将函数设为全局,因为在这种情况下它是动态生成的代码。 Is there anyway in JS that allows to call such functions ?无论如何,JS 中是否允许调用此类函数?

 // Not possible to change the structure of this file as its coming dynamically window.addEventListener("load", function() { showData(); // 1st time call function showData() { console.log('starting execution') } }); // Calling from another file showData(); // 2nd time call - not possible

No.不。

The function is declared inside another function.该函数在另一个函数中声明。 Its scope is that function.它的作用域就是那个函数。

Unless you change that code to make it a global, it isn't accessible from outside the containing function at all.除非您更改该代码以使其成为全局代码,否则根本无法从包含函数外部访问它。

If the structure of the code can't be changed, perhaps you could try attaching your function to the global window object, like:如果代码的结构无法更改,也许您可以尝试将函数附加到全局window对象,例如:

window.addEventListener("load", function() {
  // attached to window
  window.showData = function() {
    console.log('starting execution')
  };

  window.showData(); // 1st time call
    
});

// Calling from another file
window.showData();

But make sure the second call (from the other file) has a little bit of a delay (remember the eventListener has to be attached to the window first, before the function becomes available).但是请确保第二次调用(来自其他文件)有一点延迟(请记住函数可用之前,必须先将 eventListener 附加到window )。

You could try:你可以试试:

// second call
setTimeout(function() {
    window.showData();
}, 1000);

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

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