jQuery:选择器和事件

jQuery:选择器和事件

FIND ME: USING SELECTORS AND EVENTS

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined.

jQuery提供两种方式来选择元素。一种是结合CSS和XPath选择器的方式,它只需向jQuery构造器传递一个字符串即可(如,$(“div > ul a”);另一种则使用jQuery对象的多种方法。两种方式均可结合使用。

To try some of these selectors, we select and modify the first ordered list in our starterkit.

选择开头介绍的例子的订单列表并作修改,来演示一下这些选择器是怎么工作的。

To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we do it like this:

首先,选择这个列表本身。这个列表本身有一个ID“orderdlist”。在JavaScript里,可以用document.getElementById(“orderedlist”)来选取它。在jQuery中,可以这样:

 $(document).ready(function() {
   $("#orderedlist").addClass("red");
 });

The starterkit provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the first ordered list has a red background. The second list is not modified.

开头介绍的例子使用了一个样式“red”,它的作用是使背景变红。因此,当在浏览器中刷新页面时,将会首先看到这个订单列表的背景变红了。而第二个列表并没有改变。

Now lets add some more classes to the child elements of this list.

接下来给这个订单列表的子元素增加一些样式。

 $(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });

This selects all child lis of the element with the id orderedlist and adds the class "blue".

这样就选中了订单列表的所有子元素,并加上一个样式“blue”。

Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list.

现在来一些稍微复杂一点的:当用户让鼠标经过元素li上时增加和删除一个样式,要求只对列表的最后一项起作用。

 $(document).ready(function() {
   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });
 });

There are many other selectors similar to CSS and XPath syntax. More examples and a list of all available expressions can be found here.

还有许多别的类似CSS和XPath的选择器,想要更多的例子或可用的表达式的话,请点击这里。

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent.Some other events, like ready and hover, are provided as convenient methods for certain tasks.

对于可用的onxxx事件,如onclick,onchange,onsubmit,jQuery都有相应的等价的方法。其他诸如ready,hover的事件,在某些情况下可作为快捷方法使用。

You can find a complete list of all events in the jQuery Events Documentation.

在jQuery Events Documentation可以找到完整的事件列表。

With those selectors and events you can already do a lot of things, but there is more.

单单使用这些选择器,你已足以完成很多事情了,但事情远非如此。

 $(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
     $(this).append( " BAM! " + i );
   });
 });

find() allows you to further search the descendants of the already selected elements, therefore$("#orderedlist").find("li") is mostly the same as $("#orderedlist li").

find()方法允许你在选中的元素中进行更深入的查找,因此$(“#orderedlist”).find(“li”)和$(“#orderedlist li”)功能其实是一样的。

each() iterates over every element and allows further processing. Most methods, likeaddClass(), use each() themselves.

each()方法可以遍历每个元素并进一步处理每个元素。大多数的方法,如addClass()会自己调用each()方法。

In this example, append() is used to append some text to it and set it as text to the end of each element.

在这个例子中,append()用来给订单列表下的每个项追加一段文本。

Another task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

此外,你也会经常遇到要调用DOM(Document Object Model,文档对象模型)元素方法却不能用jQuery的情况,想想用AJAX该怎么提交成功后重置一个表单(form)。

 $(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });

This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

这段代码选中第一个表单元素,然后对它调用reset()方法。假使你有不只一个表单,你可以这样:

 $(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });

This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.

这段代码将会选中文档里的所有表单,迭带并重置每一个表单。注意到.each()函数,this指实际的元素。并注意到,reset()属于表单元素而非jQuery对象,我们可以更简捷地使用$(“form”).reset()来重置页面上的所有表单。

An additional challenge is to select only certain elements from a group of similar or identical ones. jQuery provides filter() and not() for this. While filter() reduces the selection to the elements that fit the filter expression, not() does the contrary and removes all elements that fit the expression. Think of an unordered list where you want to select all li elements that have no ul children.

一个额外的挑战是如何在一组相似或相同的元素中选出某些元素。jQuery为此提供了filter()和not()方法。Filter()方法把元素减少到符合过滤表达式的元素,而not()方法则移除所有符合给定表达式而保留不符合条件表达式的元素。举一个例子,怎么在一个无序列表中选出所有不具有无序子列表的列表项目。

 $(document).ready(function() {
   $("li").not(":has(ul)").css("border", "1px solid black"); 
 });

This selects all li elements that have a ul element as a child and removes all elements from the selection. Therefore all li elements get a border, except the one that has a child ul.

这段代码先选中所有列表项目,接着选中所有具有无序子列表的列表项目并全部排除,剩下的即不具有无序子列表的列表项目均加上一个外框。

The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

【表达式】的语法是XPath的用法,可以通过属性来过滤元素。有时你可能想要选出具有名字属性的所有元素的集合:

 $(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });

This adds a background color to all anchor elements with a name attribute.

这段代码实现了给所有具有名字属性的元素加上一个背景颜色。

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is (Note: This problem was fixed recently in jQuery, available in any versions after 1.1.1). To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

更经常的情况下,你不是通过名称属性来选中元素,而是想通过“href”来选。不幸的是,浏览器返回它们所认为找到了的“href”值经常不是你想要的(注:这个问题在1.1.1这后版本均已修正)。为了匹配一部分href值,可以使用包含选择“*=”代替等号(“=”):

 $(document).ready(function() {
   $("a[href*='/content/gallery']").click(function() {
     // do something with all links that point somewhere to /content/gallery
   });
 });

Until now, all selectors were used to select children or filter the current selection. There are situations where you need to select the previous or next elements, known as siblings. Think of a FAQ page, where all answers are hidden first, and shown, when the question is clicked. The jQuery code for this:

到此为止,所有示例中的选择器都用来选择子元素或者过滤当前的选择。还有一些别的情景下需要选择前一个或者后一个元素,即兄弟关系的元素。想想FAQ(Frequently Asked Questions,常见问题解答)页面,问题的答案先是被隐藏着的,当点击时出现。相应的jQuery代码如下:

 $(document).ready(function() {
   $('#faq').find('dd').hide().end().find('dt').click(function() {
     $(this).next().slideToggle();
   });
 });

Here we use some chaining to reduce the code size and gain better performance, as '#faq' is only selected once. By using end(), the first find() is undone, so we can start search with the next find() at our #faq element, instead of the dd children.

这里使用代码链的形式,以减少代码量并提高性能,因为‘#faq’只被选择过一次。end()方法的使用,结束了对前面找到“dd”时返回的元素对象的引用而直接回到#faq的引用($(‘#fap’)是.find(‘dd’)的外层,.end()只取消了.find(‘dd’)这层而跳回到$(‘#fap’)这层,参见:http://www.jquery001.com/jquery-end-method.html,jQuery end()方法详解;及官方API文档:http://api.jquery.com/end/)。

Within the click handler, the function passed to the click() method, we use $(this).next() to find the next sibling starting from the current dt. This allows us to quickly select the answer following the clicked question.

对于click事件的处理,函数传递给了click()方法,我们使用$(this).next()从当前的dt往下找到下一个兄弟元素。这样就使我们易于找到被选中问题的答案。

In addition to siblings, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

除了查找兄弟元素,还可以找到父母元素(在XPath中也被称为祖先元素)。你可能想让鼠标停留的链接的父元素高亮显示出来。试一下这样:

 $(document).ready(function(){
   $("a").hover(function(){
     $(this).parents("p").addClass("highlight");
   },function(){
     $(this).parents("p").removeClass("highlight");
   });
 });

For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

鼠标停留的所有链接的父元素都会被高亮显示,当鼠标离开时恢复原状。

Lets go one step back before continuing: jQuery is a lot about making code shorter and therefore easier to read and maintain. The following is a shortcut for the $(document).ready(callback) notation:

接着往下讲之前,让我们先来回顾一下:jQuery旨在简化代码,易于阅读和维护。以下是$(document).ready(callback)的一个简便写法:

 $(function() {
   // code to execute when the DOM is ready
 });

Applied to the Hello world! example, we end with this:

应用于Hello world!例子如下:

 $(function() {
   $("a").click(function() {
     alert("Hello world!");
   });
 });
原文地址:https://www.cnblogs.com/xiaxiazl/p/2414264.html