我的问题的一个例子可以用以下三个文件复制。。。
index.htm(索引):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
</head>
<body>
Hello, world!
</body>
</html>
$(function() {
const THE_TEXT = 'This is THE_TEXT';
});
脚本2.js:
$(function() {
function log_THE_TEXT() {
console.log(THE_TEXT);
}
log_THE_TEXT();
});
我希望在加载页面后在控制台日志中看到“这是_文本”。相反,出现了以下错误:
ReferenceError:未定义脚本2.js:6:3
jQuery.Deferred exception:未定义\文本记录\文本@
http://example.com/js-test/script2.js:6:3
更新
:感谢所有建设性地指出这是一个范围问题的人。你们都是最棒的!我觉得有点傻,因为我已经理解了PHP的作用域很多年了,但是现在我开始使用Javascript/jQuery,并且用$(function())开始这两个文件,这并没有让我明白。。。就像我在jQuery上的Udemy课程教给我的。