我有一个包含 JavaScript 的页面,该页面有一个自调用函数,该函数在页面加载时执行。此页面还包含 jquery 和 jquery ui 库(包含第一个 jquery,然后包含 jquery ui)。
以下 JavaScript 包含在页面末尾、关闭正文标记之前。
在下面的代码中,即使变量 x 和 y 正确指示 jquery ui 存在,但在 global.method1
函数中,变量 z 始终未定义,而它应该自 jquery ui 以来就已定义已加载。
问题
为什么 $.ui 定义在自调用函数之外以及同一自调用函数的文档就绪事件内,但不在 global.method1 方法内定义?
我在以下链接中有一个演示,其中我没有看到这种行为,即在 method1 $.ui 中定义:sample runnable code 。所以,这真的很令人困惑。
var x = $.ui;//defined
(function (global) {
var dialogOptions;
$(
function () {
var y = $.ui;//defined
//some more code here
}
);
global.method1 = function () {
var z = $.ui; //not defined
//some more code here
}
//some more code here
})(window);
最佳答案
我试图为您创建一个最小的示例;
- 创建了一个代码片段,其中包含指向 jQuery 的链接。
- 向控制台添加了一些日志
- 添加了对全局方法的调用
一切似乎都已定义。您的问题必须是在您的示例中未链接的代码中。
var x = $.ui; //defined
console.log(`first: ${x}`);
(function(global) {
var dialogOptions;
$(
function() {
var y = $.ui; //defined
console.log(`second: ${y}`);
//some more code here
}
);
global.method1 = function() {
var z = $.ui; //not defined
console.log(`third: ${z}`);
//some more code here
}
//some more code here
global.method1(); //added this call
})(window);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
关于javascript - 即使加载 jquery ui 库,$.ui 也是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54117189/