官术网_书友最值得收藏!

Using the $() function

The resulting set of elements from jQuery's selectors and methods is always represented by a jQuery object. Such a jQuery object is very easy to work with when we want to actually do something with the things that we find on a page. We can easily bind events to these objects and add slick effects to them, as well as chain multiple modifications or effects together.

Note

Note that jQuery objects are different from regular DOM elements or node lists, and as such do not necessarily provide the same methods and properties for some tasks. In the final part of this chapter, we will look at ways to directly access the DOM elements that are collected within a jQuery object.

In order to create a new jQuery object, we use the $() function. This function typically accepts a CSS selector as its sole parameter and serves as a factory returning a new jQuery object pointing to the corresponding elements on the page. Just about anything that can be used in a stylesheet can also be passed as a string to this function, allowing us to apply jQuery methods to the matched set of elements.

Tip

Making jQuery play well with other JavaScript libraries

In jQuery, the dollar sign ($) is simply an alias for jQuery. Because a $() function is very common in JavaScript libraries, conflicts could arise if more than one of these libraries were 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, Advanced Events.

The three primary building blocks of selectors are tag name, ID, and class. They can be used either on their own or in combination with others. The following simple examples illustrate how these three selectors appear in code:

As mentioned in Chapter 1, Getting Started, when we call methods of a jQuery object, the elements referred by the selector we passed to $() are looped through automatically and implicitly. Therefore, we can usually avoid explicit iteration, such as a for loop, that is so often required in DOM scripting.

Now that we have covered the basics, we're ready to start exploring some more powerful uses of selectors.

主站蜘蛛池模板: 丰镇市| 肥西县| 临猗县| 同江市| 大冶市| 靖边县| 屏边| 乌拉特中旗| 舞钢市| 三原县| 浦城县| 勐海县| 九寨沟县| 秦安县| 萨嘎县| 乌兰县| 繁峙县| 洛南县| 雅安市| 弋阳县| 高阳县| 鄂温| 绿春县| 茶陵县| 巴彦淖尔市| 横峰县| 陇川县| 嘉善县| 新平| 社旗县| 垣曲县| 禹城市| 临洮县| 双鸭山市| 华坪县| 大埔区| 光泽县| 白玉县| 堆龙德庆县| 东莞市| 江安县|