(3)选择元素——(3)$()方法(The $() function)

No matter which type of selector we want to use in jQuery, we always start with the same 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.

无论我们想在jquery中使用哪种类型的选择器,我们总是使用相同的函数$()开头。这个函数典型的接受一个css选择器作为他的基础的元素,然后作为一个工厂放回一个指向网页上相应元素的的新的jquery对象。任何能被样式表使用的东西都可以作为字符串传递给这个方法,允许我们把jquery方法应用到匹配的元素上。

Making jQuery play well with other JavaScript librariesIn jQuery, the dollar sign $is simply an "alias" for jQuery. As 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 jQueryin our custom jQuery code. Additional solutions to this problem are addressed in Chapter 10, Advanced Events.

使jquery和其他js库和谐相处
爱jquery中,美元符号$shi jquery的一个别名,然而一个$()方法在js的库中是很常见的,如果一个网页中使用了多个这些库,可能就会发生冲突。我们可以通过把我们的代码中所有的$替换成jquery来避免这样的冲突。这个问题的其他解决方案再第十章高级事件中介绍了。

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:

三种基本的选择器构建元素分别是tag name ckass和id他们可以单独使用,也可以和其他结合起来使用。下面的简单的例子说明了这三个选择器如何在代码中呈现的。


tag name      选择文档中所有的段落
ID                 选择文档中唯一的一个ID是some-id的元素
Class             选择文档中有着some-class这个类的元素。

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

正如第一章:入门指南中介绍的那样,当我们调用jquery对象的方法的时候,我们传递给$()的选择器选中的对象将会自动隐式的循环。因此我们通常可以避免通常在DOM脚本中需要的显式调用。

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

现在我们已经讲述过了基础知识,我们准备好了去开始探索一些更加高级的选择器的使用。

原文地址:https://www.cnblogs.com/keanuyaoo/p/3323148.html