[译]Pro ASP.NET MVC 3 Framework 3rd Edition (Chapter 20 JQuery) 4.Basic jQuery Theory --jQuery理论基础

      At the heart of jQuery is a powerful JavaScript function called jQuery (). We use it to query our HTML page’s document object model (DOM) for all elements that match a CSS selector.As a simple example, jQuery("DIV.MyClass") finds all the div elements in our DOM that have the CSS class MyClass.

     jQuery功能强大的核心函数是jQuer(),用它我们可以查询匹配CSS选择器的HTML页面的所有DOM元素。一个简单的例子,jQuery(“DIV.MyClass”)函数的作用就是在我们的DOM的所有DIV元素中查找CSS类名叫MyClass的元素。
     jQuery () returns a jQuery-wrapped set: an instance of a jQuery object that lists the results and has many extra methods you can call to operate on those results. Most of the jQuery API consists of such methods on wrapped sets. For example, jQuery("DIV.MyClass").hide() makes all the matching div elements suddenly vanish. For brevity, jQuery provides a shorthand syntax, $(), which is exactly the same as calling jQuery(). Table 20-1 contains some further examples.

   jQuery()返回一个jQuery-wrapped集:一个jQuery对象的实例,它会列出返回的结果,还包含许多可以操作这些结果的扩展方法。大多数的jQuery API都是由这样封装过的方法集合构成的。例如:jQuery(“DIV.Class”).hide()函数会隐藏掉所有匹配到的div元素。jQuery提供一个简单的语法:$(),和调用jQuery()一样的效果。表格20-1给出进一步的例子:

表格20-1. jQuery简单示例

例子 描述
$("P SPAN").addClass("SuperBig")

Adds a CSS class called SuperBig to all <span> nodes that are contained inside a <p> node

在<p>节点中的所有<span>节点添加一个叫SuperBig的CSS类标识

$(".SuperBig").removeClass("SuperBig")

Removes the CSS class called SuperBig from all nodes that have it

从所有节点中移除CSS类标识为SuperBig的元素,包含它自身。

$("#options").toggle()

Toggles the visibility of the element with ID options (if the element is visible, it will be hidden; if it’s already hidden, it will be shown)

切换ID为options的元素的可见性(如果该原色当前是显示的,它将会被隐藏;如果它当前是隐藏,会被显示)

$("DIV:has(INPUT[type='checkbox']:disabled)").prepend("<i>Hey!</i>")

Inserts the HTML markup <i>Hey!</i> at the top of all div elements that contain a disabled checkbox

在所有div元素的顶部插入一个包含了一个未选中的复选框的HTML元素<i>Hey!</i>

$("#options A").css("color", "red").fadeOut()

Finds any hyperlink tags (i.e., <a> tags) contained within the element with ID options, sets their text color to red, and fades them out of view by slowly adjusting their opacity to zero

在所有的超链接标签(即<a>标签)中查找包含了ID为options的元素,把它们的文本颜色设置为红色,通过缓慢的调整它们的不透明度为零让它们淡出我们的视野

     jQuery is extremely concise, and achieving the same effects as those produced by the examples in the table would take many lines of JavaScript. We picked the examples in the table to illustrate some of the key jQuery features, which we describe briefly in the following sections.

    jQuery是极其简练的,如果要达到表中例子所要达成的效果,Javascript则会需要多行代码才能实现。在接下来的各节我们将会通过表中的例子来简要的说明jQuery的一些关键特性。

Understanding jQuery Selectors  理解jQuery选择器

One concept key to understanding jQuery is selectors. One kind of selector is the strings that we pass to the jQuery function to specify the set of elements that we want to operate on. Listing 20-6 highlights the selector in a jQuery statement.

一个理解jQuery的关键概念就是选择器。一种选择器就是我们通过jQuery函数传递字符串给我们想要操作的指定元素。清单20-6在jQuery语句中高亮显示了这个选择器。

Listing 20-6. A jQuery Selector  清单20-6 一个jQuery选择器

$("th").toggle() 
 

The selector in this example is th, which selects all the th elements in the document. We then apply the toggle method to the selected elements. As we described in Table 20-1, the toggle method changes the visibility of elements. If we applied this jQuery statement to the HTML generated by our example project, the table headers will be hidden (and if we apply it again, they will reappear). The example in Listing 20-6 demonstrates one of the four basic selectors, which are described in Table 20-2.

在这个例子中,th是这个选择器,它在文档中选择了所有th元素,然后我们将这个切换方法应用到选中的元素。就像我们在表格20-1中描述的那样,这个切换方法(toggle())改变了这些元素的的可见性。如果我们将这些jQuery语句应用到我们示例项目生成的HTML中,标头将会被隐藏(如果我们再次应用它,它又会重新显示)。表格20-2描述了四种基础选择器,而这个例子正是其中一种。

表格20-2. jQuery基础选择器 The Basic jQuery Selectors

 

选择器 Selector 描述 Description
$('*') Selects all the elements in the document
选择文档中的所有元素
$('.myclass')

Selects all the elements to which the CSS class myclass has been assigned

选择CSS class被赋值为myclass的所有元素

$('element') Selects all the elements of the type element
选择类型为element的所有元素
$('#myid') Selects the element with the ID of myid
选择ID为myid的元素

jQuery selectors are greedy, meaning they select as many elements as they can in the HTML DOM. One exception to this is the $('#id') selector, which selects the element with the specified ID; element IDs are expected to be unique. We can narrow our selections by providing a selection context, like this:

jQuery选择是非常贪心的,意味着他们会在HTML DOM中尽可能多的选中元素,但是$(‘#id’)这个选择器是一个例外,它是根据指定的标识ID选择元素,元素的标识ID一般都是独一无二的,我们可以通过提供一个选择上下文来缩小我们的选择范围,像这样:

$('td', myElement)

which will match td elements that are descendants of myElement. You can see a selection context in use in Listing 20-17.

这条语句会匹配myElement的子节点中的td元素。你可以在清单20-17中看到这个选择上下文的用法。

A QUICK NOTE ABOUT ELEMENT IDS  快速了解元素标识

If you’re using jQuery, or in fact writing any JavaScript code to work with your MVC Framework application, you ought to be aware of how the HTML helpers render ID attributes. If we call the text box helper as follows, for example:

如果你正在使用jQuery,或者你现行的MVC框架应用中使用了一些Javascript代码,你有必要了解HTML helper类如何渲染这些标准属性。例如,我们如下所示调用text box的助手类方法:

@Html.TextBox("pledge.Amount")

it will render the following:

它将被渲染成一下HTML代码:

<input id="pledge_Amount" name="pledge.Amount" type="text" value="" />    (备注:此文电子文档id=“pledge Amount” 少了中间的’_’此处纠正)

Notice that the element name is pledge.Amount (with a dot), but its ID is pledge_Amount (with an underscore). When rendering element IDs, the built-in helper methods replace dot characters with underscores. This makes it possible to reference the elements using a jQuery selector such as $("#pledge_Amount"). Note that it wouldn’t be valid to write $("#pledge.Amount"), because in jQuery (and in CSS) that would mean an element with ID pledge and CSS class Amount. 

注意,这个元素的name是pledge.Amount(中间用一个‘.’连接),但是它的id标识是pledge_Amount(用一个下划线连接),当渲染元素标识的时候,内置的helper类的方法将用下划线替换那个点,这将使它能用类似$(“#pledge_Amount”)这样的jQuery选择器来引用这个元素。这里需要注意,$(“#pledg.Amount”)这样写是无效的,因为在jQuery(和CSS)中,这代表一个ID标识为pledge和CSS的class为Amount的元素。

备注:这里的翻译与给出的代码有些出入,为了确保翻译准确,我亲自试验了这里的代码,原英文电子文档中渲染的HTML代码为“input id="pledge Amount…”中间是空格,而非“_”,但是经过的实际测试,正确的输出应该是“pledge_Amout”,这里需要大家注意,所以这里我将英文原文和译文部分都加上了下划线。

-------------------------------------------------------------------------------------------------------

We can combine the results of multiple selectors by separating each term with a comma, as shown in Listing 20-7.

我们可以通过组合多个以逗号分隔的选择器来获取结果,如清单20-7所示:

清单20-7. 组合选择器 Combining Selections

$('td, th')

This statement selects all the td and th elements in the DOM. We can apply selections sequentially by separating the terms with spaces, as shown in Listing 20-8.

这条语句选中了在DOM中的所有td和td元素。我们可以空格分隔来应用连续的选择器,如清单20-8所示:

清单20-8. 应用多个连续的选择器 Applying Multiple Selections Sequentially

$('td input') 

In this case, we have selected all the input elements contained within td elements. In the case of our example project, this means we select the Delete buttons that are at the end of each table row but not the Reset button at the bottom of the page.

在这种情况下,我们选中了包含在td元素中的所有input元素。在我们的示例项目中,这意味着我们选择了在每行最后的删除按钮,而不是在页面底部的重置按钮。

Using Attribute Selectors 使用属性选择器

In addition to the basic selectors, there are also attribute selectors. As their name suggests, these selectors operate on attributes and their values. Table 20-3 describes the attribute selectors.

除了这些基本选择器,也有属性选择器,顾名思义,这些选择器通过属性和他们的值来操作。表20-3描述了这些选择器。

表20-3. jQuery属性选择器 The jQuery Attribute Selectors

Selector  选择器 Description 描述
$('[attr]')

Selects elements that have an attribute called attr, irrespective of the attribute value

选择属性名称叫attr的元素,不考虑属性的值

$('[attr]="val"') Selects elements that have an attr attribute whose value is val

选择attr属性值为val的元素

$('[attr]!="val"') Selects elements that have an attr attribute whose value is not val
选择attr属性值不是val的元素
$('[attr]^="val"') Selects elements that have an attr attribute whose value starts with val
选择attr属性值以val开头的元素
$('[attr]~="val"') Selects elements that have an attr attribute whose value contains val
选择attr属性值包含val的元素
$('[attr]$="val"') Selects elements that have an attr attribute whose value ends with val
选择attr属性值以val结尾的元素
$('[attr]|="val"')

Selects elements that have an attr attribute whose value is val or starts with val followed by a hyphen (val-)

选择一个attr属性值是val或者以val开头或者val后跟一个连接符(val-)的元素。

 

------------------------------------------------------------------

We can apply multiple attribute selectors together, in which case we select only those elements that match all of the conditions. Listing 20-9 contains an example.

我们也可以多个属性选择器一起应用,在这种情况下,我们仅仅能选中那些匹配了所有条件的元素。清单20-9包含了一个例子。

清单20-9. 组合属性选择器 Combining Attribute Selectors

$('[type][value="Delete"]') 

        The selects in this statement match those elements that have a type attribute (with any value) and a value attribute whose value is Delete. In the case of our example application’s HTML, this matches the Delete buttons at the end of each table row.

       这个语句选中了匹配了含有一个type属性(包含多个value属性),其中一个value属性的值为Delete的元素。在我们的HTML应用示例中,他匹配了每行最后的删除按钮。

Using jQuery Filters 使用jQuery过滤器

In addition to selectors, jQuery also supports filters, which are a convenient means for narrowing the range of elements that we select. Listing 20-10 shows an example of one of the basic filters.

除了选择器,jQuery也提供了过滤器,主要为了方便我们缩小我们选中的元素的范围。清单20-10给出了一个基本过滤器的示例。

清单20-10. 使用一个基本过滤器 Using a Basic Filter

$('td:eq(8)')

         The filter in this example is :eq(8), which selects only the ninth item in the array of elements matched by the selector (because these filters are zero-based). Table 20-4 describes the basic filters.

       在这个示例中,过滤器是eq(8),它仅仅选中了根据选择器匹配出来的元素数组中的前8项(因为这些过滤器都是从零开始的)。表20-4描述了这些基本过滤器。

表20-4.jQuery基本过滤器  The jQuery Basic Filters

Filter 过滤器 Description  描述
:eq(n) Selects the n-1th item in the selection
选择所选内容的第n-1项

:even
:odd

Selects the even-numbered or odd-numbered elements
选择偶数或者奇数元素

:first
:last

Selects the first or last element
选择第一个或者最后一个元素

:gt(n)
:lt(n)

Selects all the elements whose index is greater or less than n
选择所有元素中索引大于或者小于n的元素
:header Selects all elements that are headers (h1, h2, and so on)
选择所有header头元素(h1,h2等等)
:not(selector) Selects all the elements that do not match the selector
选择所有不被选择器匹配中的元素

The filters can be used in conjunction with selectors, as shown in Listing 20-10, or on their own, as demonstrated in Listing 20-11.

过滤器可以和选择器组合使用,如清单20-10中所示,单独的使用方式见清单20-11.

清单20-11. 单独使用过滤器 Using a Filter Without a Selector

$(':header')

In this example, we have used the :header filter to select all the headers. When we do this, the universal selector (*) is implied. We could have achieved the same result by using a selector that combined all the header element types ($('h1 h2 h3')), but using the filter is simpler and easier. We can combine multiple filters by appending them together, as shown in Listing 20-12.

在这个示例中,我们使用:header过滤器选中了所有的header,当我们做这些的时候,选中所有的选择器(*)是隐式的,我们通过一个组合了所有header元素类型($(‘h1 h2 h3’))的选择器也可以达到同样的效果,但是显而易见,使用过滤器是更简单、更容易的。我们可以通过把更多的过滤器追加在一起组合使用,如清单20-12所示。

清单20-12. 应用多个过滤器 Applying Multiple Filters

$('td:odd:eq(1)') 

This selects the td element, filters them so that only the odd-numbered items remain, and then selects the second element. 

选中td元素,然后过滤它们,保留奇数项,然后选中其中的第二项元素。

Using Content Filters 使用内容过滤器

The next filters we will look at are content filters, which are described in Table 20-5. These filters are focused on the content of an element, both in terms of text and other elements.

我们一起看的下一个过滤器是内容过滤器,在表20-5中会看到对它的描述,这些过滤器的重点是元素的内容,无论是元素的文本还是其他元素。

表20-5. jQuery内容过滤器 The jQuery Content Filters

Filter 过滤器 Description 描述
:contains('text') Selects elements that contain text or whose children contain text
选择包含text或者它们的子元素包含text的元素
:has('selector') Selects elements that have at least one child element that matches selector
选择至少一个子元素匹配selector的元素
:empty Selects elements that have no child elements
选择没有子元素的元素
:parent Selects elements that have at least one other element
选择有至少一个其他元素的元素(就是父元素,下面要有子元素的意思。译者加)
:first-child Selects elements that are the first child of their parent
选择父元素下的第一个子元素
:last-child Selects elements that are the last child of their parents
选择父元素下的最后一个子元素
:nth-child(n) Selects elements that are the nth child of their parent
选择父元素下的第n个子元素
:only-child Selects elements that are the only child of their parent
选择父元素下唯一的子元素

A little caution is required when using the :contains filter because it matches elements that contain the specified text and elements whose children contain it. This means that if we use the filter on its own against the HTML generated by our example application, like this:

有一点需要我注意的是,在我们使用:contains过滤器的时候,它只会匹配那些它或者它的子元素包含了指定文本和元素的元素。这意味着,如果我们将这个过滤器用在我们示例应用生成的HTML上,像这样:

$(':contains("K2")')

then we select six elements: the td element that contains the text and all of this element’s parents (tr, tbody, table, body, and html elements).

那么,我们选择6个元素:包含了这个文本的td元素以及这个元素所有的父级元素(tr,tbody,table,body,和html元素)。

Caution:To preserve compatibility with CSS conventions, the nth-child filter is one-based. In other words, if you want to select elements that are the first child of their parent, use :nth-child(1) and not :nth-child(0).

警告:与CSS约定保持兼容,第n个子过滤器是基于第一个的,换句话说,如果你想选择的元素是某个父级元素的首个子元素,可以使用:nth-child(1) 而不是:nth-child(0)。

Using Form Filters  使用表单过滤器

The final filters we will describe are the form filters, which are convenient for selecting elements related to HTML forms. Table 20-6 describes these elements. 

我们最后要描述的过滤器是表单过滤器,它便于我们选择与HTML表单相关的元素,表20-6描述了这些元素。

表20-6. jQuery表达过滤器 The jQuery Form Filters

Filter过滤器 Description 描述
:button Selects button elements and input elements whose type is button
选择input类型为button的按钮元素
:checkbox Selects checkboxes
选择复选框(checkbox)
:checked Selects checkboxes and radio button elements that are checked
选择状态是checked的复选框(checkbox)和单选(radio)按钮元素

:disabled
:enabled

Selects items that are enabled or disabled, respectively
分别选择启用或禁用的项
:input Selects input elements
选择input元素
:password Selects password elements
选择密码(password)元素
:radio Selects radio buttons
选择单选(radio)按钮
:reset Selects input elements whose type is reset
选择input类型为reset的元素
:selected Selects option elements that are selected
选择option项状态为selected的元素
:submit Selects input elements whose type is submit
选择input类型为submit类型的元素
:text Selects input elements whose type is text
选择input类型为text的元素

Understanding jQuery Methods 理解jQuery方法

         Selectors and filters let us tell jQuery which elements we want to work with. Methods are how we tell jQuery what to do. We have shown a few jQuery methods so far, such as toggle, but jQuery is a very capable library, and many methods are available. In the sections that follow, we’ll show you some of the most useful methods and demonstrate their effect. For further details and a complete list of the methods that jQuery supports, see http://jquery.com.

       选择器和过滤器让我们告诉jQuery哪些元素是我们需要处理的元素。方法则是我们告诉jQuery要做什么,到现在为止,我们已经展示过一些jQuery方法,像toggle,但是jQuery是个功能非常强大的库,它提供了很多方法供我们使用。在接下来的小节,我们会给你展示一些最常用的方法并且让你看到它们的效果。jQuery所提供的方法的完整列表和详细信息,请查看 http://jquery.com

Waiting for the DOM 等待DOM

We showed you the selectors and filters in isolation because a selector or filter on its own does nothing. Now that we are ready to combine our selections with methods, we can start to add jQuery scripts to our MVC Framework application’s view. Listing 20-13 shows the skeletal view into which we will add our jQuery statements.

我们向你分开展示选择器和过滤器,因为它们自身不做任何事情,现在我们准备好方法,结合我们的选择器,我们可以将jQuery脚本添加到我们的MVC框架应用视图。清单20-13展示了将要添加我们的jQuery榆木的skeletal视图。

清单20-13.Skeletal视图  The Skeletal View

@using MvcApp.Models; 

@model IEnumerable<Summit> 

@{ 

    ViewBag.Title = "List of Summits"; 

} 

@if (false) { 

    <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script> 

} 

<script type="text/javascript"> 

    $(document).ready(function () { 

        // our jQuery code will go here 

    });  

</script> 

<h4>Summits</h4> 

<table> 

    <thead> 

        <tr><th>Name</th><th>Height</th></tr> 

    </thead> 

    @foreach (Summit s in Model) { 

        <tr> 

            <td>@s.Name</td> 

            <td>@s.Height</td> 

            <td> 

                @using (Html.BeginForm("DeleteSummit", "Home")) { 

                    @Html.Hidden("name", @s.Name) 

                    <input type="submit" value="Delete" />    

                } 

            </td> 

        </tr> 

    } 

</table> 

@Html.ActionLink("Add", "AddSummit") 

@using (Html.BeginForm("ResetSummits", "Home")) { 

    <input type="submit" value="Reset" /> 

} 

       We have added our script element to the view itself, which means the scripts that we add will take effect only when this view is rendered. If we want scripts that are performed for multiple views, then we can add them to a layout.

     我们将我们的脚本元素加入到了视图本身,这意味着我们添加的脚本仅在渲染呈现这个视图时生效。如果我们想要脚本能够被多个视图执行,我们可以将它们添加到布局中。

Tip: We don’t need to reference the jQuery library file in our view because it is referenced in the layout instead, as shown in Listing 20-3. We have, however, added a reference to the vsdoc file so that we benefit from IntelliSense for jQuery.

小提示:我们不需要在我们的视图中引用jQuery的库文件,因为它将在布局中被引用,就像清单20-3所展示的那样。不管怎么样,为了我们能够受益于jQuery的智能感知,我们已经添加了一个引用到vsdoc文件中。

        We have added the $(document).ready() function to our script element. This is a useful feature that means our jQuery code won’t be executed until after the DOM is loaded but before any media (including images) are available. This is a matter of timing. We don’t want our code to be executed too soon, because not all of the elements that we want to work with will be known to the browser. We don’t want to wait for the media to load, because this can take a while, and the user may have already started interacting with the page. We will use the $(document).ready() function in all the examples in this chapter.

        我们添加了$(document).ready()函数到我们的脚本元素中,这是一个有用的特性,这意味着我们的jQuery代码将会在DOM加载完毕之后加载,但是会在一些媒体文件(包含图片)加载完毕前加载。这是个时间顺序的问题,我们不希望我们的代码被过早的执行,因为此时并不是所有我们需要处理的元素都被加载到了浏览器,我们不想等待加载媒体文件,因为这需要一段时间,而我们的用户已经准备好和页面进行交互了。我们会在本章节所有的例子中使用$(document).ready()这个函数。

Using jQuery CSS Methods使用jQuery的CSS方法

The best place to start applying jQuery in our example application is in the area of CSS. Using the jQuery CSS-related methods, we can significantly improve the appearance of our content. Listing 20-14 shows an example of combining jQuery selectors and CSS methods to our HTML table.

在我们的示例应用中使用jQuery最好的地方就是在CSS区域。使用jQuery中与CSS有关的方法,我们可以大大的改善内容的外观显示。清单20-14展示了一个在HTML表格元素中加入结合jQuery选择器和CSS方法的示例。

清单20-14.使用一些jQuery的CSS方法  Using Some of the jQuery CSS Methods

@using MvcApp.Models; 

@model IEnumerable<Summit> 

@{ 

    ViewBag.Title = "List of Summits"; 

} 

@if (false) { 

    <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script> 

} 

<script type="text/javascript"> 

    $(document).ready(function () { 

        $('table').addClass('summitTable'); 

        $('tr:even').css('background-color', 'silver'); 

        $(':submit[value="Reset"], a:contains("Add")') 

            .css('float', 'left') 

            .css('margin', '5px'); 

    }); 

</script> 

<h4>Summits</h4> 

<table> 

    <thead> 

        <tr><th>Name</th><th>Height</th><th/></tr> 

    </thead> 

    @foreach (Summit s in Model) { 

        <tr> 

            <td>@s.Name</td> 

            <td>@s.Height</td> 

            <td> 

                @using (Html.BeginForm("DeleteSummit", "Home")) { 

                    @Html.Hidden("name", @s.Name) 

                    <input type="submit" value="Delete" />    

                } 

            </td> 

        </tr> 

    } 

</table> 

@Html.ActionLink("Add", "AddSummit") 

@using (Html.BeginForm("ResetSummits", "Home")) { 

    <input type="submit" value="Reset" /> 

} 

        This is the last time that we’ll show the entire view. From now on, we’ll just list the jQuery script, since the rest of the view won’t change from example to example.

        这是我们最后一次展示整个视图的代码,从现在开始,我们仅列出jQuery脚本,因为在以后的例子中,视图的其余部分将不会改变。

        The listing contains three CSS-related operations. The first is as follows:

        清单包含了三个于CSS相关的操作,第一个是:

$('table').addClass('summitTable');

        The addClass method adds a CSS class to the selected elements, in this case, the table element. We defined the summitTable class in the Site.css file, which is referenced in the layout, as follows:

        addClass方法向选择的元素添加一个CSS类,这种情况下,我们在Site.css文件中定义这个在布局中被引用的summitTable类,如下所示:

.summitTable  

{ 

    border: thin solid black; 

    margin: 5px;     

} 

        The addClass method doesn’t check to see that the summitTable class exists; it just manipulates the element so that the class attribute is added, like this:

        addClass方法并不会去检查summitTable类是否存在,它只是操作该元素以使该类属性被添加,像这样:

<table class="summitTable">

        The next statement performs what is known as zebra-striping. This is a popular effect that increases the readability of grids:

        下一条待执行的语句被称为zebra-striping,这是非常流行的效果,提高了网格的可读性:

$('tr:even').css('background-color', 'silver');

        The css method modifies the style attribute of the selected elements to set the value (silver) for a specified style property (background-color). The selector in this statement selects the even-numbered tr elements. Zero is an even number in zero-based counting systems, which means that the table rows with indexes 0, 2, 4, 6, and so on, are modified as follows:

        这个css方法修改了被选择元素的样式属性,设置其指定的样式属性(background-color)的值为silver。这条语句中的选择器选择了偶数的tr元素,0在计数系统中是一个偶数,也就意味着索引是0,2,4,6等等的行会被选择,修改如下:

       <tr style="background-color: silver; ">

USING J QUERY METHOD OVERLOADS 使用jQuery方法重载

Many jQuery methods have several overloaded versions that take different numbers of arguments. For example, when the css method is used with one argument, like this:

很多jQuery方法都有提供了采用不同数目参数的重载版本,举个例子,当这个css方法是使用一个参数时,像这样:

$('tr:first').css('background-color')

then the method just returns the current value of the specified style element, in this case, the background-color value. This value can then be used as an argument to other methods, like this:

那么该方法只返回指定样式元素的当前值,在这种情况下,就是这个backgroud-color的值,而这个值可以随后用于作为其他方法的参数,像这样:

$('tr').css('background-color', $('tr:first').css('background-color'))

which sets the background-color for all tr elements to match that of the first tr element.

用来为所有tr元素匹配那首个tr元素设置背景颜色(backgroud-color)。

The final statement demonstrates that we can chain jQuery methods together, as follows:

将jQuery方法链接在一起作为我们最后一个演示语句,如下所示:

$(':submit[value="Reset"], a:contains("Add")') 

    .css('float', 'left') 

    .css('margin', '5px'); 

        The selector in this example matches the two elements at the bottom of the page: the Add link and the Reset button. We set a value for two different styles by applying the css method to the results generated by a previous call to the css method. Method chaining is one of the key characteristics of a fluent API, which can make coding simpler and code easier to read. Most of the jQuery methods return a collection of jQuery elements on which further methods can be called. Our example showed only two CSS-related methods. Table 20-7 describes the most useful CSS-related methods that jQuery supports.

        在我们这个例子中的选择器匹配了在页面底部的两个元素:一个添加(Add)链接和重置(Reset)按钮。我们通过由前一个调用CSS方法产生的结果应用到一个CSS方法中来为两个不同的样式设定值。方法连接是一个流畅的API的关键特征之一,它使编码变得简单,而且便于阅读。大部分jQuery方法都会返回一个可以进一步调用的jQuery元素集合,我们的示例中只展示了两个与CSS相关的方法。表20-7描述了jQuery支持的最有用的,与CSS相关的方法。

表20-7.jQuery的CSS方法  The jQuery CSS Methods

Method 方法 Description 描述
addClass('myClass') Adds the specified class name to the class attribute of selected elements
给选择的元素的类属性添加指定的类名
hasClass('myClass')

Returns true if the any of the selected elements have been assigned the specified class

如果选择的元素含有指定的类则返回true

removeClass('myClass')

Removes the specified class name from the class attribute of selected elements

从选择的元素的类属性中移除指定的类名

toggleClass('myClass') Adds the specified class if it isn’t present and removes it otherwise
如果指定的类不存在,则添加;否则,删除它。
css('property', 'value')

Adds the specified property and value to the style attribute of selected elements

给选择的元素的样式属性添加指定的属性和值

         Although it can be useful to manipulate CSS when the DOC loads, these methods are often combined with jQuery events to change the appearance of HTML elements in response to an event occurring; see the “Using jQuery Events” section later in this chapter for more details of how jQuery handles events. Figure 20-6 shows the effect of the CSS changes performed by the script in Listing 20-14.

       尽管它可以用于DOC加载时操作CSS,这些方法通常是结合jQuery事件在响应事件的发生时改变HTML元素的外观;在此章随后的“使用jQuery事件”部分会有更多详细介绍关于jQuery如何处理事件。图20-6展示了20-14脚本清单执行的CSS变化效果。

image

图:20-6  使用jQuery操作CSS Using jQuery to manipulate CSS

Tip :In addition to these methods, there are others that can be used to read or write elements’ style properties directly, including height(), width(), and position(). See the jQuery API reference for further details.

小提示 :除了这些方法以外,也有一些可以直接读写元素样式属性的方法,包括 height(),width()和position(),查看jQuery API的定义可以获取更详细的信息。

Working with the DOM 使用DOM

jQuery’s support for manipulating the DOM is so comprehensive that we can only just scratch the surface in this book. We can add, remove, and change DOM elements, and we can even move elements from one part of the DOM to another. In this section, we’ll provide some basic examples, but a full appreciation of the jQuery DOM capabilities requires diligent perusal of the API reference and some careful experimentation. Listing 20-15 demonstrates creating new elements in the DOM and using jQuery to add a new column to the table to express the heights of the summits in feet.

jQuery对操作DOM的支持是非常全面的,在这本书书里,我们仅仅对它进行浅显的研究,我们可以添加、删除和修改DOM元素,甚至我们可以把元素从DOM的一部分移动到其他部分。在这部分,我们会提供一些基本的示例,但是要透彻理解jQuery DOM的功能需要认真阅读它的API文档,细心的做一些试验。清单20-15展示了在DOM中添加一个新的元素并且使用jQuery往表中添加一个新列用来描述从山脚到山峰的高度。

清单20-15. 给DOM添加一个新元素

<script type="text/javascript"> 

 

    $(document).ready(function () { 

 

        $('table').addClass('summitTable'); 

        $('tr:even').css('background-color', 'silver'); 

        $(':submit[value="Reset"], a:contains("Add")') 

            .css('float', 'left') 

            .css('margin', '5px'); 

 

        $('th:nth-child(2)').text('Height (m)').after('<th>Height (ft)</th>'); 

        $('td:nth-child(2)') 

            .after('<td/>') 

            .each(function () { 

                $(this).next().text((parseInt($(this).text()) * 3.28).toFixed(0)); 

            }); 

    }); 

 

</script> 

        There are only two new statements in this script, but because of the expressive nature of jQuery and the support for method chaining, there is a lot going on. Let’s start with the first statement:

        在这个脚本里只有两条新语句,但是根据jQuery要表的本质和它支持的方法链,还有很多需要说明,让我们从第一条语句开始:

$('th:nth-child(2)').text('Height (m)').after('<th>Height (ft)</th>');

        We start by selecting those th elements that are the second children of their parent. The only set of th elements in our sample HTML is in the table element, and the one that is the second child is the Height header. We use the text method to set the text context of the selected element to Height (m) to indicate that this column in the table contains the height of the summits expressed in meters. We then chain the after method that inserts a new element as a peer to the selected element. The parameter for the after method is the element we want to insert, which in this case is a new th element with the text content Height (ft).

      我们开始选择的是任何父节点里的第二个th元素。在我们的示例中,仅仅是table元素中需要对th元素设置,而且匹配上第二个子元素的要求,就是高度的表头。我们使用text方法去设置选中元素的文本上下文,以Height (m) 来表示在表中包含了山峰高度的列,然后我们链接之后的方法,插入一个与选定元素同级的新元素.之后方法的参数是我们要插入的元素,在这种情况下,就是一个新的包含了Height (ft).文本的th元素。

        When we use the after method, the new element is inserted after each selected element. We selected only one th element, so only one new element was created. With the second jQuery statement, however, we created several:

       当我们使用之后的方法,会在每个选定的元素后插入新元素。我们只选择了一个th元素,所有也只有一个新的元素被创建。然而,用第二条语句,我们创建了好几个新的元素:

$('td:nth-child(2)') 

    .after('<td/>') 

    .each(function () { 

        ... 

    }); 

        The selector in this statement matches any td element that is the second child of its parent. We are selecting the td elements from the Height column (which has now been renamed Height (m), of course).

       语句里的选择器匹配任何父节点里的第二个td元素,我们从高度列选择td元素(当然,现在已经被更名为Height(m)了)。
        We then chain a call to the each method, which accepts as its parameter a function that will be executed for each selected element. Our function contains a single statement:

       然后,我们链接一个对each方法的调用,函数作为参数被接收,对每个选中的元素执行该调用。我们的函数包含了一个单独的语句:

$(this).next().text((parseInt($(this).text()) * 3.28).toFixed(0)); 

         We start with a special selector, $(this), which creates a selection that contains the element currently being processed. The function we pass to the each method is executed once for each selected element, and this refers to the element that the function is being called for. We need to pass this to the main jQuery function so that we can call methods on the element. In this case, the selector this will refer to each of the td elements that we queried for initially.

        我们以一个特殊的选择器$(this)开始,它创建了一个包含当前被处理元素的选择。我们传递给each方法的函数为每个选中的元素执行一次,而且this涉及了被函数调用的元素。我们需要把this传递给jQuery的主函数,以便我们能够在元素上调用方法。this选择器会涉及我们最初查询的每个td元素

         We call the next method to select the sibling immediately after the current element. This gives us the element we just created. We then use the text method to get the text content of one td element and to set the content of another. We calculate the height in feet in the client (1 meter is 3.28 feet).

       我们调用next方法选择紧邻当前元素后面的同辈元素,正是我们刚刚创建的元素。然后,我们使用text方法获取一个td元素的文本内容并设置为我们在客户端所计算的山脚高度(1米=3.28英尺)。

Figure 20-7 shows the new column.  图20-7展示了新列

image

图 20-7. 用jQuery添加新内容 Adding new content using jQuery

              We picked this example for two reasons. The first is it uses different types of jQuery DOM methods. We use after to create a new element and next to navigate through the DOM. The second reason is that there are several different ways of performing the task. This is not uncommon in jQuery, where we can combine different methods to similar effect. Listing 20-16 shows an alternative script that adds the new column.

          我们采用这个例子主要有两个原因,第一个就是它使用不同类型的jQueryDOM方法,我们使用后创建的新元素,并在下一步浏览DOM。第二个原因就是可以有多个不同的方式去执行一个任务。结合不同的方法达到相似的效果,这在jQuery中是不常见的。清单20-16展示了一种另类的添加新列的脚本

清单20-16. An Alternative Approach to Adding Content to the Summits Table 一种给Summits表添加内容的另类方法

$('th:nth-child(2)').text('Height (m)').after('<th>Height (ft)</th>'); 

$('td:nth-child(2)').each(function () { 

    var height = (parseInt($(this).text()) * 3.28).toFixed(0); 

    $('<td/>').insertAfter($(this)).text(height).css('border', 'thin solid red'); 

}); 

The key difference is the statement shown in bold. In the previous example, we used the after method. The result of this method is the selected element, not the element we just created. Any method that we chain to after will be applied to the original element. The statement in Listing 20-16 uses the insertAfter method, which has the same effect as after but returns the newly created element, meaning that any chained methods are applied to the new element and not the existing one (you will also notice that we specify the new element in the main jQuery function and the existing element as the parameter to the insertAfter method). This means we can apply methods to the newly created elements without having to select them or navigate to them. As a demonstration, we added a CSS border, as shown in Figure 20-8.

关键区别在于黑体显示的部分,在前面的示例中,我们采用的是后面的那种方法,这个方法的结果是选中的元素并不是我们刚刚创建的那个元素。我们后面所链接的一些方法都会被直接作用于原始元素。清单20-16使用了insertAfter方法,执行效果和after一样,但是它会返回最新创建的元素,这意味这那些链接方法会被作用于新元素而不是已经存在的元素(你应该也会注意到我们在jQuery的主函数中指定的新元素和在insertAfter方法中作为参数的已经存在的元素)。这意味着我们可以将方法作用到最近创建的元素上,而不必选中它们或者导航到它们。作为示范,我我们添加了一个CSS 边框,如图20-8所示

image

图20-8. 利用不同的方法创建元素A different approach to creating elements

             The point is that there are often different ways to achieve the same goal, and it is worth experimenting with varying approaches to find one that does what you need in a way that is robust and you are comfortable with. Table 20-8 shows some common jQuery DOM-related manipulation, but quite a number are available, and you should consult the jQuery API reference for the full set.

            这一点就是说通常完成同一个目标可以用不同的方式、途径,表20-8列出了一些公用的,jQuery中与DOM操作相关的方法,如果你想获取更多,需要查阅jQueryAPI文档。
表20-8.挑选出来的一些和DOM操作相关的jQuery方法 Selected jQuery DOM Manipulation Methods

Method方法 Description描述

before('new')
after('new')

Inserts the element new either before or after the selected elements.
在选中的元素前面或者后面插入元素new

insertBefore()
insertAfter()

As for before and after, but the order of the new element and the selector is reversed, and these methods return the newly created elements. See Listing 20-16 for an example.

和before与after方法相比,new元素的顺序和选择器的位置是相反的,而且它们会返回最近创建的元素,清单20-16给出了一个示例

prepend('new')
append('new')

Inserts the element new inside of the selected elements, either as the first or last child.

在选中的元素中插入一个元素new,或者作为它的第一个或者最后一个子元素

prependTo()
appendTo()

As for prepend and append, but the order of the new element and the selector is reversed, and these methods return the newly created elements.

和prepend与append方法相比,new元素的顺序和选择器的位置是相反的,而且它们会返回最近创建的元素。

empty() Removes all children from the selected elements.
清空选中元素的子元素
remove() Removes the selected elements from the DOM.
从DOM中移除选中的元素
attr('name', 'val')

Sets the attribute name to value val on the selected elements; will create the attribute if it doesn’t already exist.

给选中的元素设置name属性的值为val;如果不存在name属性则创建它

removeAttr('name') Removes the attribute name from the selected elements.
把选中元素的name属性移除

            jQuery also defines a set of methods for navigating around the DOM. Table 20-9 shows some of the most commonly used of these.

           jQuery 也定义了一组用于浏览DOM的方法集。表20-9列出了一些总常用的方法
表20-9. 挑选出来的用于浏览DOM的jQuery方法 Selected jQuery DOM Navigation Methods

Method方法 Description描述
children() Gets the children of the selected elements
获取选中元素的子元素
next() Gets the sibling elements that immediately follow the selected elements
获取紧邻选中元素的下一个元素
prev() Gets the sibling elements that immediately precede the selected elements
获取紧邻选中元素的前一个元素
parent() Returns the immediate parents of the selected elements
获取选中元素的父级元素
sibilings() Returns the siblings of the selected elements
获取选中元素的兄弟元素

           The navigation methods accept an optional selector parameter; only elements that match the selector will be returned as results.

         这些方法接收一个可选的选择器作为参数;只有被选择器匹配到元素才会被返回。

《此小节完毕,有翻译不准确的地方,请回复或私信,因工作繁忙,下面的翻译不定期,有时间就翻译….》

你可能感兴趣的:(framework)