javascript - 如何访问文件外的函数
问题描述
我的问题是如何访问在其他文件中创建的函数。我有 3 个文件checkSelection.js
polishToEnglish.js
polishToGerman.js
。
文件1的结构是:
//some code
function selectOptions() {
//some code
if (document.getElementById("Pol2Eng").checked) {
polishToEnglish(polish2EnglishDictionaryPath, polishExpression);
} else if (document.getElementById("Pol2Ger").checked) {
polishToGerman(polish2EnglishDictionaryPath, polish2GermanDictionaryPath, polishExpression);
}
//some code
}
第二个是:
function polishToEnglish(polish2EnglishDictionaryPath, polishExpression){
//some code
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
var lines = xmlhttp.responseText;
dictionary = lines.split('\n');
return findTranslation(dictionary, polishExpression);
}
};
//some code
}
function findTranslation(dictionary, word) {
dictionary.forEach(function(line){
if(line.includes(word)) {
result = line.split(';')[1];
}
});
return result;
}
第三个是:
function polishToGerman(polish2EnglishDictionaryPath, polish2GermanDictionaryPath, polishExpression) {
engWord = polishToEnglish(polish2EnglishDictionaryPath, polishExpression);
}
问题出在第三个文件中。engWord
显示为未定义。我尝试了一些解决方案,例如制作函数window.polishToEnglish = function(...){}
,但没有效果。任何想法如何解决这个问题?
解决方案
简单的解决方案:以正确的顺序链接到它们。所以:
<script src="polishToEnglish.js">
<script src="polishToGerman.js">
<script src=checkSelection.js">
因为checkSelection
使用来自其他两个文件的声明,并且polishToGerman
依赖于polishToEnglish
.
(更好的解决方案是使用某种模块,例如 ES6 的export
-import
或 CommonJS 和module.exports
- require
)。
推荐阅读
- python - 集成 Python 和 C++ 代码时如何修复抛出错误?我将函数从 Python 调用到 C++ 的方式有问题吗?
- php - php.ini 在服务器重新启动后不反映更改
- vue.js - Vuetify3 如何定义主题设置
- python - 将一个数据帧中的值附加或连接到 Pandas 中另一个数据帧中的每一行
- python - 将 .shp 文件查询到 Excel 时如何解决错误?
- powershell - 在 If 条件下验证字符串不为空/null
- d3.js - 使用 D3 和 D3Plus 更改文本中的一种单词颜色
- kubernetes - 集群资源管理器中集群应用程序部分中的牧场主链接自定义服务
- design-patterns - REST API 客户端设计 - 最佳实践
- google-bigquery - 删除括号 bigquery 之间的所有内容