javascript jQuery:如何使用“$”而不是“jQuery”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6635600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: How can I use "$" instead of "jQuery"?
提问by Linksku
I have simple jQuery in my site, yet I keep getting this error:
我的网站中有简单的 jQuery,但我不断收到此错误:
Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function
The error only appears if I use "$" instead of "jQuery".
只有当我使用“$”而不是“jQuery”时才会出现错误。
// This works
jQuery(document).ready(function() {
jQuery('#pass').keyup( ... );
});
// This doesn't
$(document).ready(function() {
$('#pass').keyup( ... );
});
Do I need to do anything to use "$"?
我需要做什么才能使用“$”吗?
回答by anton_byrna
You can wrap your code:
您可以包装您的代码:
(function($) {
// here $ would be point to jQuery object
$(document).ready(function() {
$('#pass').keyup( ... );
});
})(jQuery);
回答by Dan Smith
You probably have jQuery noConflict mode enabled somewhere in your code, see: http://api.jquery.com/jQuery.noConflict/
您可能在代码中的某处启用了 jQuery noConflict 模式,请参阅:http://api.jquery.com/jQuery.noConflict/
jQuery.noConflict(); // Stops $ from workng
回答by Clueless
First, jQuery objects are a lot like arrays, so [object DOMWindow]
actually isa jQuery object most likely.
首先,jQuery 对象很像数组,因此[object DOMWindow]
实际上最有可能是jQuery 对象。
You might have a syntax error, like a missing semicolon, right before the call to $(document)
which is making the $
look like a property access.
您可能有一个语法错误,比如缺少分号,就在调用$(document)
它之前,它$
看起来像一个属性访问。