简体   繁体   English

尝试使用从另一个页面加载的 function 导致 function 未定义

[英]Trying to use a function loaded from another page results in function undefined

i am using fetch to load a page code (html & js ) from another page then insert that code to be able to use it.我正在使用 fetch 从另一个页面加载页面代码(html 和 js),然后插入该代码以便能够使用它。

   fetch('site.com')
    .then(response=>response.text())
    .then(data=>{ document.body.innerHTML += data })

after that i try to call a function called dosubmit() that's in the other page code but it gives me之后,我尝试调用另一个页面代码中的名为 dosubmit() 的 function,但它给了我

dosubmit is not defined dosubmit 未定义

even though that the request loaded successfully.即使请求成功加载。

Javascript execution happens when html page gets loaded. Javascript 执行发生在 html 页面加载时。 After page has loaded, and you are trying to inject the Javascript code won't help.页面加载后,您尝试注入 Javascript 代码将无济于事。

There are some ways though to achieve this,有一些方法可以实现这一点,

  1. You can make use of eval()您可以使用 eval()
  2. You can dynamically insert a separate js file having your code (In your case dosubmit())您可以动态插入包含您的代码的单独 js 文件(在您的情况下为 dosubmit())

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

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