在Jquery中最根本的方法就是jQuery(),它是jquery的根本。
有的朋友可能会奇怪,为什么和你的标题中的工厂方法不一致呢?
呵呵,其实$()是jQuery()的简写形式。但是这个简写形式在给我们带来便利的同时,也会带来一些麻烦:
因为在其它的一些JS框架里,$()是经常被使用的,所以如果你使用了jquery的同时,还引用了其它的JS框架的话,就会产生冲突(据说是有其它的解决方法,我还不知道呢,请各位指正吧),这时你就不能用$()这种简写形式了。
不过签于Jquery的强大功能,把其它的框架都去掉吧:-)
$()方法的参数可以是任何形式的字符,返回值是一个jQuery对象。例如:
$('div'):表示取出页面中的所有div元素,并返回一个jQuery对象。
注:对象可以理解为一个特殊形式的容器,比如一辆宝马汽车,就是汽车的一个具体对象,包含汽车的基本特征。
没想到我这个JQ菜鸟的几句话,引起了大家这么多的意见;-),看来我还是要深入的去学习,下面我把我的参考资料帖出来:
节选自《Learning Jquery》:
The $() Factory Function
No matter which type of selector we want to use in jQuery—be it CSS, XPath, or custom—we always start with the dollar sign and parentheses: $()
As mentioned in Chapter 1, the $() function removes the need to do a for loop to access a group of elements since whatever we put inside the parentheses will be looped through automatically and stored as a jQuery object. We can put just about anything inside the parentheses of the $() function. A few of the more common examples include:
A tag name: $('p') gets all paragraphs in the document.
An ID: $('#some-id') gets the single element in the document that has the corresponding some-id ID.
A class: $('.some-class') gets all elements in the document that have a class of some-class.
Making jQuery Play Well with Other JavaScript Libraries
In jQuery, the dollar sign $ is simply shorthand for jQuery. Because a $()
function is very common in JavaScript libraries, conflicts could arise if more than one of these libraries is being used in a given page. We can avoid such conflicts by replacing every instance of $ with jQuery in our custom jQuery code. Additional solutions to this problem are addressed in Chapter 10.
••
•Now that we have covered the basics, we're ready to start exploring some more powerful uses of selectors.