有一种非常常见的技术是编写 $
而不是 jQuery
并将其包装在一个函数中:
(function($) {
//Code here
})(jQuery);
现在,这个问题是,你在一个小的本地范围内,这在大多数情况下很好,但如果你试图调用一个函数名通过字符串构造动态地:
let dynamic_name = some_function_name; //but should be dynamic, duh
window[dynamic_name]();
将无法工作,因为您在该本地范围内操作,而不是在 window
范围内操作,并且它将无法找到该函数,例如:
(function($) {
//If we put this outside of this scope, it works.
function test() {
console.log('test');
}
let name = 'test';
window[name]();
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
这也意味着如果您的脚本被用作库,您的函数将不可调用,因为您将它们包装在匿名函数中。
您究竟是如何解决这个问题的?
最佳答案
显式地将函数分配给window
:
(function($) {
window.test = function test() {
console.log('test');
}
let name = 'test';
window[name]();
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
或者将函数放在一个对象中:
(function($) {
//If we put this outside of this scope, it works.
const fns = {
test() {
console.log('test');
}
};
let name = 'test';
fns[name]();
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
这实际上与 jQuery 没有任何关系 - 在任何 IIFE 或任何不在顶层的 block 中都可以看到相同类型的行为(和解决方案)。
关于javascript - 如何在不包装匿名函数的情况下使用 jQuery 的美元符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57735075/