简体   繁体   English

如何使addEventListener在单独的文件中适用于Javascript函数?

[英]How to make addEventListener work for Javascript functions in a separate file?

I currently have document.addEventListener('DOMContentLoaded', functionName); 我目前有document.addEventListener('DOMContentLoaded', functionName); which passes the following function as the parameter: 它通过以下函数作为参数:

function functionName() {
  $.ajax({
    type: 'GET',
    url: '/populatePage',
    success: function(data) {
      createPage(data);
    }
  })
}

Problem Description: 问题描述:

When the function above is in the same javascript file as the line document.addEventListener('DOMContentLoaded', functionName); 当上面的函数与document.addEventListener('DOMContentLoaded', functionName);行位于同一JavaScript文件中时document.addEventListener('DOMContentLoaded', functionName); the page loads properly. 页面正确加载。

But when the function is saved in a separate javascript file and then included in the file with the line above, the page does not load. 但是,如果将函数保存在单独的javascript文件中,然后将其包含在上面的行中,则不会加载该页面。

I'm probably missing something basic here, but can anyone please explain? 我可能在这里缺少一些基本的知识,但是谁能解释一下吗?

Make it global function. 使其具有全局功能。 It's not advisable but if you want quick solution then 不建议这样做,但是如果您想快速解决问题,那么

window.functionName = function() {
  $.ajax({
    type: 'GET',
    url: '/populatePage',
    success: function(data) {
      createPage(data);
    }
  })
}

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

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