[英]jQuery's dollar syntax vs dollar sign JavaScript "convention"
I've read here that for JavaScript there's a "convention" that the $
function be defined as a shortcut for document.getElementById
, so I've defined the following function in a <script>
,我在这里读到 JavaScript 有一个“约定”,即
$
函数被定义为document.getElementById
的快捷方式,所以我在<script>
定义了以下函数,
function $(x) { return document.getElementById(x); }
so I could write $('main')
instead of document.getElementById('main')
, for instance.所以我可以写
$('main')
而不是document.getElementById('main')
,例如。
Soon after, when I started looking into jQuery, I found that jQuery uses the syntax $( selector ). action ()
不久之后,当我开始研究 jQuery 时,我发现 jQuery 使用语法
$( selector ). action ()
$( selector ). action ()
extensively . $( selector ). action ()
广泛。
However, the two solutions don't seem to work nicely together.但是,这两种解决方案似乎不能很好地协同工作。
Are indeed the two mutually exclusive?两者真的是互斥的吗? As in, if I use jQuery, I can't use the
$
function above, and if I use the latter I can't use jQuery?比如,如果我使用 jQuery,我就不能使用上面的
$
函数,如果我使用后者,我就不能使用 jQuery?
You can use jQuery.noConflict
to return control of $
.您可以使用
jQuery.noConflict
返回$
控制权。 Then, to use jQuery, use jQuery
instead of $
.然后,要使用 jQuery,请使用
jQuery
而不是$
。
jQuery.noConflict();
jQuery('#main')
You can also assign the returned value of noConflict
to an object, and use it just like $
:您还可以将
noConflict
的返回值分配给一个对象,并像$
一样使用它:
var a = jQuery.noConflict();
a('#main')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.