jQuery in Action 中文版 第一章 jQuery简介 如翻译的不好请原谅

 

1 Introducing jQuery 1    1.jQuery 简介

 

1.1 Why jQuery? 2  为啥要用jquery

1.2 Unobtrusive JavaScript 3 初涉jquery

1.3 jQuery fundamentals 5 jquery 基础

The jQuery wrapper 6(包) Utility functions(公共函数) 8 The document

ready handler$()函数) 9 Making DOM elementsDOM元素处理) 11 Extending

jQueryjQuery 扩展 12 Using jQuery with other librariesjquery 舍我其谁 14

1.4 Summary小结 14

                                                                                                                                               1.1 Why jQuery?

If you’ve spent any time at all trying to add dynamic functionality to your pages,

you’ve found that you’re constantly following a pattern of selecting an element or

group of elements and operating upon those elements in some fashion. You

could be hiding or revealing the elements, adding a CSS class to them, animating

them, or modifying their attributes.

如果你随时花时间为你的页面动态添加函数,你会发现你经常选中一个或多个元素并且操作他们,隐藏或启用元素,添加css,动画,修改属性

Using raw JavaScript can result in dozens of lines of code for each of these

tasks. The creators of jQuery specifically created the library to make common

tasks trivial. For example, designers will use JavaScript to “zebra-stripe” tables—

highlighting every other row in a table with a contrasting color—taking up to 10

lines of code or more. Here’s how we accomplish it using jQuery:

如果用原来Javascript随便实现功能都需要,几十行代码。jQuery作者很明确就是要使普通的应用简单化,举例说明:如果要实现表格斑马纹需要10行以上的代码,但是jQuery只要如下的代码

$("table tr:nth-child(even)").addClass("striped");

Don’t worry if that looks a bit cryptic to you right now. In short order, you’ll understand

how it works, and you’ll be whipping out your own terse—but powerful—

不用担心现在看起来对你有点神秘,马上你就会理解,简介但是很强大

jQuery statements to make your pages come alive. Let’s briefly examine how this

code snippet works.

jQuery使你的页面变活了,简单的分析一下这个代码段

We identify every even row (<tr> element) in all of the tables on the page and

add the CSS class striped to each of those rows. By applying the desired background

color to these rows via a CSS rule for class striped, a single line of Java-

Script can improve the aesthetics of the entire page.

我们认为每个偶数行在表格所在的页面中添加斑马纹样式,通过应用期望的背景颜色,javascript能改善整个页面的美感

When applied to a sample table, the effect could be as shown in figure 1.1.

The real power in this jQuery statement comes from the selector, an expression

for identifying target elements on a page that allows us to easily identify and grab

the elements we need; in this case, every even <tr> element in all tables. You’ll

find the full source for this page in the downloadable source code for this book in

file chapter1/zebra.stripes.html.

效果如上图所示,jQuery的真正力量在选择器,一个表达式确认页面中的元素,方便我们抓取我们你需要的元素,这个例子中是全部的偶数行。你能在下载下来的文件中找到这个例子chapter1/zebra.stripes.html.

We’ll study how to easily create these selectors; but first, let’s examine how the

inventors of jQuery think JavaScript can be most effectively used in our pages.

我们将学习如何轻松的创建这些选择器,首先让我们看看作者的想法对我们会更有用

1.2 Unobtrusive JavaScript(初设javascript

Remember the bad old days before CSS when we were forced to mix stylistic

markup with the document structure markup in our HTML pages?

记得css之前我们被迫使用最少的样式在文档结构中。

Anyone who’s been authoring pages for any amount of time surely does and,

perhaps,@@@ with more than a little shudder. The addition of CSS to our web development

toolkits allows us to separate stylistic information from the document

structure and give travesties like the <font> tag the well-deserved boot.

有点不寒而栗,样式独立于HTML文档,就不会出现一些像<font>比较可笑的哦标记

Not only does the separation of style from structure make our documents easier to manage, but it also gives us the versatility to completely change the stylistic rendering

of a page by swapping out different stylesheets.

Few of us would voluntarily regress back to the days of applying style with

HTML elements; yet markup such as the following is still all too common:

样式独立于文档结构除了管理法方便,对样式的呈现也可以通过换样式文件改变显示。没有人愿意回到以前样式与文档结构一起的时候。然而下面的的处理方式还是普遍存在。

<button

type="button"

onclick="document.getElementById('xyz').style.color='red';">

Click Me

</button>

We can easily see that the style of this button element, including the font of its

caption, is not applied via the use of the <font> tag and other deprecated style oriented

markup, but is determined by CSS rules in effect on the page.

在按钮的标题上应用了字体,但是不是由<font>等样式标签来实现的,坚决用css规则来作用于页面。

But although this declaration doesn’t mix style markup with structure, it does mix

behavior with structure by including the JavaScript to be executed when the button is

clicked as part of the markup of the button element (which in this case turns some

Document Object Model [DOM] element named xyz red upon a click of the button).

For all the same reasons that it’s desirable to segregate style from structure

within an HTML document, it’s as beneficial (if not more so) to separate the behavior

from the structure.

尽管这种声明不是最小的样式标签对于文档结构,但是这是最小的行为对于这个结构,通过包含javascript来执行按钮的点击事件。种种原因,大家都希望从文档中分离样式,有利于分离行为。

This movement is known as Unobtrusive JavaScript, and the inventors of jQuery

have focused that library on helping page authors easily achieve this separation

in their pages.

Jquery作者的把焦点放在了帮助我们达到分离js与页面的效果

 Unobtrusive JavaScript, along with the legions of the jQuery-savvy,

considers any JavaScript expressions or statements embedded in the <body> of

HTML pages,

沿着智能理解jauqry表达式和嵌入式jquery

either as attributes of HTML elements (such as onclick) or in script

blocks placed within the body of the page, to be incorrect.

“But how would I instrument the button without the onclick attribute?”

把标签或者脚本块放在页面中是不合理的,但是我们如何接收单击事件没有单击属性呢?

You might ask. Consider the following change to the button element:

你也许会思考改编成下面的方式

<button type="button" id="testButton">Click Me</button>

Much simpler! But now, you’ll note, the button doesn’t do anything.

Rather than embedding the button’s behavior in its markup, we’ll move it to a

script block in the <head> section of the page, outside the scope of the document

body, as follows:

这么简单,但是现在请注意,按钮不做任何事情,而不是嵌入事件到标签中,而是要把脚本块放到<head>中,不要放在<body>中,如下:

<script type="text/javascript">

window.onload = function() {

document.getElementById('testButton').onclick = makeItRed;

};

function makeItRed() {

document.getElementById('xyz').style.color = 'red';

}

</script>

We place the script in the onload handler for the page to assign a function, make-

ItRed(), to the onclick attribute of the button element.

把函数makeItRed()放在onload中调用,应用于按钮的单击属性

We add this script in the onload handler (as opposed to inline) because we need to make sure that the button

element exists before we attempt to manipulate it.

把脚本添加到onload中,是为了确保在调用的时候,按钮已经加载进来,

(In section 1.3.3 we’ll see how jQuery provides a better place for us to put such code.)

If any of the code in this example looks odd to you, fear not! Appendix A provides

a look at the JavaScript concepts that you’ll need to use jQuery effectively.

如果你觉得这些代码对你来说有点困难,附录A提供了一些javascript的基本概念,说明如何让jquery能够正确运行

We’ll also be examining, in the remainder of this chapter, how jQuery makes writing

the previous code easier, shorter, and more versatile all at the same time.

我会注意在后面的章节中,把代码写的又容易理解,又简短,又通用

Unobtrusive JavaScript, though a powerful technique to further add to the

clear separation of responsibilities within a web application, doesn’t come without

its price.

这种强大的技术更加清楚了分离的智者,不用就体现不出它的价值了

You might already have noticed that it took a few more lines of script to

accomplish our goal than when we placed it into the button markup. Unobtrusive

JavaScript not only may increase the amount of script that needs to be written,

but also requires some discipline and the application of good coding patterns to

the client-side script.

可能你已经注意到,这种脚本块比放在按钮的标签中行数要多,原始的javascript不但有可能增加更多的脚本,还需要训练和好的模式

None of that is bad; anything that persuades us to write our client-side code

with the same level of care and respect usually allotted to server-side code is a

good thing! But it is extra work—without jQuery.

虽然这也不是啥坏事,这让我们把前台脚本和和后台代码放在了同样的地位上,也是好事,但是这就增加了工作如果不用jQuery

As mentioned earlier, the jQuery team` has specifically focused jQuery on the

task of making it easy and delightful for us to code our pages using Unobtrusive

JavaScript techniques, without paying a hefty price in terms of effort or code bulk

in order to do so.

像前面说的,jQuery小组专注于能简单的快乐的让我们既能达到目的,又不需要花大力气和很多的代码

 We’ll find that making effective use of jQuery will enable us to

accomplish much more on our pages by writing less code.

有效的使用jQuery,实现同样的效果,使用很少的代码

Without further ado, let’s start taking a look at just how jQuery makes it so

easy for us to add rich functionality to our pages without the expected pain.

言归正传,看看jQuery如何简单的添加丰富多彩的功能却没有预料的那么痛苦

1.3 jQuery fundamentals

At its core, jQuery focuses on retrieving elements from our HTML pages and performing

operations upon them.

jQuery重点关注从页面获取和操作标签

If you’re familiar with CSS, you’re already well

aware of the power of selectors, which describe groups of elements by their

attributes or placement within the document.

如果你熟悉css你就知道选择器的强大,css通过属性和位置描述标签组

With jQuery, you’ll be able to leverage

your knowledge and that degree of power to vastly simplify your JavaScript.

通过jQuery 就能够平衡你对js的认识(可能是相对css),极大的简单你的javascript

jQuery places a high priority on ensuring our code will work in a consistent

manner across all major browsers;

jQuery能在各大浏览器中保持高度一致性

 many of the more difficult JavaScript problems,

such as waiting until the page is loaded before performing page operations, have

been silently solved for us.

许多javascript问题,比如等待页面加载完成(onload),都已经不知不觉中得到了解决

Should we find that the library needs a bit more juice, its developers have built

in a simple but powerful method for extending its functionality. Many new jQuery

programmers find themselves putting this versatility into practice by extending

jQuery on their first day.

开发人员能构建简单但是强大的功能对jQuery进行扩展,许多jQuery开发人员发现自己也能开发丰富多彩的功能,通过扩展jQuery

But first, let’s look at how we can leverage our CSS knowledge to produce powerful,

yet terse, code.

首先,看看如何通过css开发强大的功能并且简单的代码

1.3.1 The jQuery wrapper

1.3.1 jQuery

When CSS was introduced to web technologies in order to separate design from

content, a way was needed to refer to groups of page elements from external

style sheets. The method developed was through the use of selectors, which concisely

represent elements based upon their attributes or position within the HTML document.

Css作为分离网页内容的技术,css通过外部样式表文件定义页面一组的元素的样式 ,是通过选择器,通过属性和位置表现元素。

For example, the selector

p a

refers to the group of all links (<a> elements) that are nested inside a <p> element.

jQuery makes use of the same selectors, supporting not only the common selectors

currently used in CSS, but also the more powerful ones not yet fully implemented

by most browsers.

引用一组嵌套在p标签中的a标签,jquery使用了相同的选择器,不但支持类似于css格式,也支持更加强大的应用与大多数的浏览器。

The nth-child selector from the zebra-striping code we

examined earlier is a good example of a more powerful selector defined in CSS3.

To collect a group of elements, we use the simple syntax

nth-child选择器 我们是试验过斑马线代码,这是一个一个非常好的例子,在css3中也有相同的定义

获取一组标签,jQuery也是用相同的语法

$(selector)

or

jQuery(selector)

Although you may find the $() notation strange at first, most jQuery users

quickly become fond of its brevity.

For example, to retrieve the group of links nested inside a <p> element, we use

the following

尽管你可能刚开始觉得$()表示法有点奇怪,大多数jQuery很快就会发现这是多么的简洁

$("p a")

The $() function (an alias for the jQuery() function) returns a special Java-

Script object containing an array of the DOM elements that match the selector.

This object possesses a large number of useful predefined methods that can act

on the group of elements.

$()jquery的别名,$()返回一个选择器匹配上的多元素javascript对象,并且可以调用大量的预定义的函数。

In programming parlance, this type of construct is termed a wrapper because it

wraps the matching element(s) with extended functionality. We’ll use the term

jQuery wrapper or wrapped set to refer to this set of matched elements that can be

operated on with the methods defined by jQuery.

这种设计的语法结构称作包,因为包含了匹配上的元素,通过这种包,来操作匹配上的元素。

Let’s say that we want to fade out all <div> elements with the CSS class not-

LongForThisWorld. The jQuery statement is as follows:

class等于notLongForThisWorlddiv加上淡出的效果,语句如下:

$("div.notLongForThisWorld").fadeOut();

A special feature of a large number of these methods, which we often refer to as

jQuery commands, is that when they’re done with their action (like a fading-out

operation), they return the same group of elements, ready for another action. For

example, say that we want to add a new CSS class, removed, to each of the elements

in addition to fading them out. We write

我们引用大量的jquery方法,这些方法返回原来的元素数组,以备其他方法引用。

举个例子,我们除淡出效果之外想为所有的的元素添加新的class=removed

$("div.notLongForThisWorld").fadeOut().addClass("removed");

These jQuery chains can continue indefinitely. It’s not uncommon to find examples

in the wild of jQuery chains dozens of commands long. And because each

function works on all of the elements matched by the original selector, there’s no

need to loop over the array of elements.

这些jquery链一直这么链接下去,我们不难发现jquery有几十个函数相连。每个函数都是通过选择器匹配的元素们来调用的,不需要循环这些元素数组。

It’s all done for us behind the scenes!因为他已经封装毫克不需要我们关心

Even though the selected group of objects is represented as a highly sophisticated

JavaScript object, we can pretend it’s a typical array of elements, if necessary.

As a result, the following two statements produce identical results:

即使,选中的对象数组表示智能javascript对象,但是我们如果需要的话可以认为他就是典型的元素数组

下面两种语句产生相同的结果

$("#someElement").html("I have added some text to an element");

or

$("#someElement")[0].innerHTML =

"I have added some text to an element");

Because we’ve used an ID selector, only one element will match the selector. The

first example uses the jQuery method html(), which replaces the contents of a

DOM element with some HTML markup. The second example uses jQuery to

retrieve an array of elements, select the first one using an array index of 0, and

replace the contents using an ordinary JavaScript means.

因为使用了ID选择器,只有一个元素会被匹配,第一个例子:用了html(),html标签替(I have added some text to an element)换DOM 元素,第二个例子:用jquery获取元素数组,用索引0选择第一个,用javascript普通的方法替换内容

If we want to achieve the same results with a selector that resulted in multiple

matched elements, the following two fragments would produce identical results:

如果要匹配上的多元素达到相同的结果,下面就是

$("div.fillMeIn")

.html("I have added some text to a group of nodes");

var elements = $("div.fillMeIn");

for(i=0;i<elements.length;i++)

elements[i].innerHTML =

"I have added some text to a group of nodes";

As things get progressively more complicated, leveraging jQuery’s chainability

will continue to reduce the lines of code necessary to produce the results that you

want. Additionally, jQuery supports not only the selectors that you have already

come to know and love, but also more advanced selectors—defined as part of the

CSS Specification—and even some custom selectors.

随着学习的深入,利用jquery的可函数连接的特性,我们还可以减少代码的行数。另外 jquery不只是支持你看到的这么些,还有进一步类似于css格式的选择器,甚至自定义的选择器

Here are a few examples.下面是一些例子

$("p:even");

This selector selects all even <p> elements.

这个选择器匹配索引为偶数的全部<P>标签

$("tr:nth-child(1)");

This selector selects the first row of each table.

这个选择器匹配每个表格的第一行

$("body > div");

This selector selects direct <div> children of <body>.

这个匹配<body>的直接<div>标签,就是直接包含在body中,没有其他标签包含在div外面

$("a[href$=pdf]");

This selector selects links to PDF files.

匹配a标签,并且href属性以PDF结尾

$("body > div:has(a)")

This selector selects direct <div> children of <body>-containing links.

这个匹配<body>的直接<div>标签,就是直接包含在body中,没有其他标签包含在div外面

并且div中包含a标签

Powerful stuff! 作者自夸,不用理会

You’ll be able to leverage your existing knowledge of CSS to get up and running

fast and then learn about the more advanced selectors jQuery supports.

你可以利用你掌握的css的一些东西,来运行的更好,再慢慢学习更多的高级的选择器

We’ll be covering jQuery selectors in great detail in section 2.1, and you can find a

full list at http://docs.jquery.com/Selectors.

后面还不会补充一些更相信的选择器在2.1章节,或者到http://docs.jquery.com/Selectors.查看全部列表

Selecting DOM elements for manipulation is a common need in our pages, but

some things that we also need to do don’t involve DOM elements at all. Let’s take

a brief look at more that jQuery offers beyond element manipulation.

选择DOM元素来处理是页面普遍的需求,但是有许多时候在元素处理之外还有其他的需求,我们简要的看一下这种元素外的处理。

1.3.2 Utility functions

1.3.2 公共函数

Even though wrapping elements to be operated upon is one of the most frequent

uses of jQuery’s $() function, that’s not the only duty to which it’s assigned. One of

its additional duties is to serve as the namespace prefix for a handful of generalpurpose

utility functions. Because so much power is given to page authors by the

jQuery wrapper created as a result of a call to $() with a selector, it’s somewhat rare

虽然我们经常使用$()来匹配操作元素组,不过他还有其他的功能,作为命名空间前缀,在他下面有一些通用的函数,如$.函数名()

for most page authors to need the services provided by some of these functions; we

won’t be looking at the majority of these functions in detail until chapter 6 as a

preparation for writing jQuery plug-ins.

大部分页面开发人员需要一些现成可以调用的函数的函数,但是我们不需要非常详细的理解这么多的函数,到第六章会有详细的介绍,这里就作为到时候写插件的准备

But you will see a few of these functions

put to use in the upcoming sections, so we’re introducing their concept here.

The notation for these functions may look odd at first. Let’s take, for example,

the utility function for trimming strings. A call to it could be

但是在接下来的章节中我们会看到一些这种函数,所以先在这里做一下介绍,这种写法刚看起来可能有点怪异,

举个例子 公共函数trim,作用去掉字符串两边的空格

$.trim(someString);

If the $. prefix looks weird to you, remember that $ is an identifier like any other

in JavaScript. Writing a call to the same function using the jQuery identifier,

rather than the $ alias, looks a bit more familiar:

如果你觉得$.前缀有点有点怪异,你只要记住他是jQuery标识符的别名。

jQuery.trim(someString);

Here it becomes clear that the trim() function is merely namespaced by jQuery or

its $ alias.

这下就清楚了,trim只不过是jQueryjQuery的别名$的函数。

NOTE Even though these elements are called the utility functions in jQuery documentation,

it’s clear that they are actually methods of the $() function.

注意,虽然我们看到是元素调用的这些公共函数,实际上他们是$的函数。

We’ll put aside this technical distinction and use the term utility function to

describe these methods so as not to introduce conflicting terminology

with the online documentation.

我们使用公共函数来描述这些方法,以便不和在线文档冲突,

We’ll explore one of these utility functions that helps us to extend jQuery in section

1.3.5, and one that helps jQuery peacefully coexist with other client-side

libraries in section 1.3.6. But first, let’s look at another important duty that

jQuery’s $ function performs.

为了扩展大家多jQuery的认识我们会在1.3.5章节中研究一个公共函数,在章节1.3.6介绍使jQuery能和其他脚本库共存的函数

1.3.3 The document ready handler

1.3.4 文档加载完成函数 ready

When embracing Unobtrusive JavaScript, behavior is separated from structure,

so we’ll be performing operations on the page elements outside of the document

markup that creates them. In order to achieve this, we need a way to wait until

the DOM elements of the page are fully loaded before those operations execute.

In the zebra-striping example, the entire table must load before striping can

be applied.

拥抱无侵入(不在html文档从嵌入脚本)脚本,js行为从html文档中分离,我们执行对页面元素的操作在文档的外部引用js,要达到这个目的,我们必须等页面完全加载完成,才能实行操作,在斑马线的例子中,对斑马线的效果应用必须等整个表格加载完成。

Traditionally, the onload handler for the window instance is used for this purpose,

executing statements after the entire page is fully loaded. The syntax is typically

something like

习惯上,onload事件是window实例声明在页面加载完成后执行,经典的用法如下

window.onload = function() {

$("table tr:nth-child(even)").addClass("even");

};

This causes the zebra-striping code to execute after the document is fully loaded.

Unfortunately, the browser not only delays executing the onload code until after

the DOM tree is created but also waits until after all images and other external

resources are fully loaded and the page is displayed in the browser window. As a

result, visitors can experience a delay between the time that they first see the page

and the time that the onload script is executed.

斑马线例子的中代码是在页面加载完成才执行,但是不幸的是浏览器需要等待DOM树和图片外部资源全部加载完成页面显示出来后才执行,结果访问者的体验需要等到页面显示出来后才执行脚本。

Even worse, if an image or other resource takes a significant time to load, visitors

would have to wait for the image loading to complete before the rich behaviors

become available. This could make the whole Unobtrusive JavaScript movement a

non-starter for many real-life cases.

更加糟糕的是,如果图片或者其他资源需要比较长时间才能加载完成,访问者就需要等待图片全部加载完成,许多案例中无侵入脚本就不是在DOM一加载完成就执行

A much better approach would be to wait only until the document structure is

fully parsed and the browser has converted the HTML into its DOM tree form

before executing the script to apply the rich behaviors. Accomplishing this in a

cross-browser manner is somewhat difficult, but jQuery provides a simple means

to trigger the execution of code once the DOM tree, but not external image

resources, has loaded.

比较好的是文档和DOM树一加载完成就执行脚本,要完成跨浏览器实现这种功能就比较难,但是jQuery提供一个简单的方法当DOM树加载完成就执行脚本,而不需要等待图片等资源全部加载。

The formal syntax to define such code (using our striping example) is as follows:

格式如下:

$(document).ready(function() {

$("table tr:nth-child(even)").addClass("even");

});

First, we wrap the document instance with the jQuery() function, and then we

apply the ready() method, passing a function to be executed when the document

is ready to be manipulated.

首先通过jQuery函数打包文档实例,然后调用ready方法,最后当文档ready就执行里面的代码

We called that the formal syntax for a reason; a shorthand form used much

简洁的写法如下:

more frequently is as follows:

$(function() {

$("table tr:nth-child(even)").addClass("even");

});

By passing a function to $(), we instruct the browser to wait until the DOM has

fully loaded (but only the DOM) before executing the code. Even better, we can

use this technique multiple times within the same HTML document, and the

browser will execute all of the functions we specify in the order that they are

declared within the page. In contrast, the window’s onload technique allows for

only a single function. This limitation can also result in hard-to-find bugs if any

third-party code we might be using already uses the onload mechanism for its

own purpose (not a best-practice approach).

通过$()函数,我们就可以指引浏览器一加载完成DOM树就执行,甚至还可以在一个页面中多次的使用,浏览器会按照声明的顺序依次执行,相比之下windowonload只允许一些简单的函数 ,如引用第三方代码放在onload中很难找出bug

We’ve seen another use of the $() function; now let’s see yet something else

that it can do for us.

我们看到了$()不同的用法,接下来就来看看它还能做啥

1.3.4 Making DOM elements

It’s become apparent by this point that the authors of jQuery avoided introducing

a bunch of global names into the JavaScript namespace by making the $() function

(which you’ll recall is merely an alias for the jQuery() function) versatile enough to

perform many duties. Well, there’s one more duty that we need to examine.

We can create DOM elements on the fly by passing the $() function a string

that contains the HTML markup for those elements. For example, we can create a

new paragraph element as follows:

不难看出作者通过$()避免了一大堆的javascript命名空间的解释,你可能只记住了$()只是jQuery别名,但是$()却足够来完成各种功能。 下面就让我们做个测试,我们用$("<p>Hi there!</p>")来创建DOM元素

$("<p>Hi there!</p>")

But creating a disembodied DOM element (or hierarchy of elements) isn’t all that

useful; usually the element hierarchy created by such a call is then operated on

using one of jQuery’s DOM manipulation functions.

创建一个空洞的DOM元素没啥作用,必须通过函数操作他们,才有意义

Let’s examine the code of listing 1.1 as an example.

例子如下

<html>

<head>

<title>Follow me!</title>

<script type="text/javascript" src="../scripts/jquery-1.2.js">

</script>

<script type="text/javascript">

$(function(){

$("<p>Hi there!</p>").insertAfter("#followMe");//<p>Hi there!</p>插在ID= followMe的元素后面

});

</script>

</head>

<body>

<p id="followMe">Follow me!</p>

</body>

</html>

This example establishes an existing HTML paragraph element named followMe c in the document body. In the script element within the <head> section, we

establish a ready handler b that uses the following statement to insert a newly

created paragraph into the DOM tree after the existing element:

$("<p>Hi there!</p>").insertAfter("#followMe");

The result is as shown in figure 1.2.

这个例子首先确定有个元素的ID=followMe,通过$("<p>Hi there!</p>")创建元素,插在followMe元素后面.

We’ll be investigating the full set of DOM manipulation functions in chapter 2,

where you’ll see that jQuery provides many means to manipulate the DOM to

achieve about any structure that we may desire.

在第二章我们会研究DOM操作函数,会看到Jquery的许多操作的DOM的方法

Now that you’ve seen the basic syntax of jQuery, let’s take a look at one of the

most powerful features of the library.

现在 即将会看到基础的jQuery语法,瞧瞧jQuery类库中的新内容

1.3.5 Extending jQuery

1.3.5 扩展 jQuery(言外之意就是插件喽)

The jQuery wrapper function provides a large number of useful functions we’ll

find ourselves using again and again in our pages. But no library can anticipate

everyone’s needs. It could be argued that no library should even try to anticipate

every possible need; doing so could result in a large, clunky mass of code that

contains little-used features that merely serve to gum up the works!

jQuery中含有大量的函数,但是不可能满足每个人的需求,但是没有一种库能够预见每个人的需求,如果把所有的需求都考虑进去,库就会变得很大实用性就会很差,只能越来越糟

The authors of the jQuery library recognized this concept and worked hard to

identify the features that most page authors would need and included only those

needs in the core library. Recognizing also that page authors would each have

their own unique needs, jQuery was designed to be easily extended with additional

functionality.

jQuery类库的作者承认很难在核心库中包含所有开发人员需要的内容,jQuery设计的初衷是方便扩张。

But why extend jQuery versus writing standalone functions to fill in any gaps?

That’s an easy one! By extending jQuery, we can use the powerful features it

provides, particularly in the area of element selection.

jQuery通过函数来扩展是非常方便的,我们能用它提供的功能来的扩展,特别是在元素的处理方面。

Let’s look at a particular example: jQuery doesn’t come with a predefined function

to disable a group of form elements. And if we’re using forms throughout our

application, we might find it convenient to be able to use the following syntax:

看一个特殊例子,disable元素组的函数并不是预定义的函数,你会发现很容易写出下面的语句

$("form#myForm input.special").disable();

Fortunately, and by design, jQuery makes it easy to extend its set of functions by

extending the wrapper returned when we call $().

幸运的是,我们通过调用$()很容易扩展函数集

Let’s take a look at the basic idiom for how that is accomplished:

瞧瞧下面基础的书写特点,多么的有灵活

$.fn.disable = function() {

return this.each(function() {//这个this指向调用disable的包

if (typeof this.disabled != "undefined") this.disabled = true;//这个this指向迭代中包中当前元素

});

}

A lot of new syntax is introduced here, but don’t worry about it too much yet. It’ll

be old hat by the time you make your way through the next few chapters; it’s a

basic idiom that you’ll use over and over again.

我们介绍了大量的语法,凡是别担心他多你无法记住,通过后面章节你慢慢就会熟悉,这些都是基础的语法你会经常用到。

First, $.fn.disable means that we’re extending the $ wrapper with a function

called disable. Inside that function, this is the collection of wrapped DOM elements

that are to be operated upon

.

Then, the each() method of this wrapper is called to iterate over each element

in the wrapped collection. We’ll be exploring this and similar methods in greater

detail in chapter 2.

Inside of the iterator function passed to each(), this is a

pointer to the specific DOM element for the current iteration. Don’t be confused

by the fact that this resolves to different objects within the nested functions. After

writing a few extended functions, it becomes natural to remember.

首先,我们通过$.fn.disable来扩展$,调用disableDOM元素包里面的元素将会不断调用this.disabled = true;

在第二章我们将研究类似的大量方法

迭代是通过each函数来实现的,each中的this指向了当前的迭代元素,多写几个这种扩展函数自然就记住了

 

For each element, we check whether the element has a disabled attribute, and

if it does, set it to true. We return the results of the each() method (the wrapper)

so that our brand new disable() method will support chaining like many of the

native jQuery methods. We’ll be able to write

每个元素不管他是否有disable属性都把disable设为true,并且还反$()包,所以disable()函数支持后面接着链接函数,就像jQuery自带的函数一样

$("form#myForm input.special").disable().addClass("moreSpecial");

From the point of view of our page code, it’s as though our new disable()

method was built into the library itself! This technique is so powerful that most

new jQuery users find themselves building small extensions to jQuery almost as

soon as they start to use the library.

disable方法加到jQuery类库,是多么的强,许多人开始用就扩展jQuery类库

Moreover, enterprising jQuery users have extended jQuery with sets of useful

functions that are known as plugins. We’ll be talking more about extending jQuery

in this way, as well as introducing the official plugins that are freely available in chapter 9.

此外,比较好学的还把扩展的方法一插件的方式加到jQuery,后面会更多的讨论这方面,就像介绍jQuery本身的类库一样在第九章

Before we dive into using jQuery to bring life to our pages, you may be wondering

if we’re going to be able to use jQuery with Prototype or other libraries

that also use the $ shortcut. The next section reveals the answer to this question.

你可能有疑问当如何让jQuery和其他的脚本类库同时在页面中使用,当其他的脚本也使用$关键字,下一章节会揭示答案

1.3.6 Using jQuery with other libraries

Even though jQuery provides a set of powerful tools that will meet the majority of

the needs for most page authors, there may be times when a page requires that

multiple JavaScript libraries be employed. This situation could come about

because we’re in the process of transitioning an application from a previously

employed library to jQuery, or we might want to use both jQuery and another

library on our pages.

尽管jQuery提供了强大的类库,但是有时候我们可能需要包括jQuery在内的多种类库一起使用,可能是因为要从其他类库过度到jQuery类库,也有可能需要同时使用多种类库。

The jQuery team, clearly revealing their focus on meeting the needs of their

user community rather than any desire to lock out other libraries, have made provisions

for allowing such cohabitation of other libraries with jQuery on our pages.

jQuery团队清楚的知道必须关注使用者的需求,而不希望把其他的类库排斥在外,并且已经给出了和其他类库共处的方法。

First, they’ve followed best-practice guidelines and have avoided polluting the

global namespace with a slew of identifiers that might interfere with not only

other libraries, but also names that you might want to use on the page. The identifiers

jQuery and its alias $ are the limit of jQuery’s incursion into the global

namespace.

首先 要方便使用,避免干扰其他类库和开发人员可能用到的名字,关键字jQuery和化名$是造成入困扰的主要问题。

Defining the utility functions that we referred to in section 1.3.2

定义公共函数在1.3.2中已经归类总结过

As part of the jQuery namespace is a good example of the care taken in this regard.

Although it’s unlikely that any other library would have a good reason to

define a global identifier named jQuery, there’s that convenient but, in this particular

case, pesky $ alias. Other JavaScript libraries, most notably the popular

Prototype library, use the $ name for their own purposes. And because the usage

of the $ name in that library is key to its operation, this creates a serious conflict.

The thoughtful jQuery authors have provided a means to remove this conflict

with a utility function appropriately named noConflict().

jQuery命名空间这点上,尽管其他类库叫jQuery的可能性不大,但是$这个化名就比较讨厌了,在几大流行的类库中都使用了$,而且都是作为关键字来使用,这就造成了许多矛盾,jQuery的作者经过深思熟虑提供了方法(公共函数noConglict())来解决这个矛盾。

Anytime after the conflicting libraries have been loaded, a call to jQuery.noConflict();

will revert the meaning of $ to that defined by the non-jQuery library.

We’ll further cover the nuances of using this utility function in section 7.2.

调用jQuery.noConflict()就会取消$jQuery的定义,后面我们会涉及到其他的公共函数

1.4 Summary

In this whirlwind introduction to jQuery we’ve covered a great deal of material in

preparation for diving into using jQuery to quickly and easily enable Rich Internet

Application development.

在不断的介绍中我们为快速开发和实现更丰富的效果做了大量的准备

jQuery is generally useful for any page that needs to perform anything but the

most trivial of JavaScript operations, but is also strongly focused on enabling

page authors to employ the concept of Unobtrusive JavaScript within their pages.

With this approach, behavior is separated from structure in the same way that CSS

separates style from structure, achieving better page organization and increased

code versatility.

jQuery在页面表示中是全能的,但却省掉了许多繁琐的操作,但是他更注重开发人员能够无入侵开发(与页面HTML代码分离)

就像css一样,

Despite the fact that jQuery introduces only two new names in the JavaScript

namespace—the self-named jQuery function and its $ alias—the library provides

a great deal of functionality by making that function highly versatile; adjusting

the operation that it performs based upon its parameters.

 

尽管jQUery命名空间只有jQuery$但是却提供大量功能强大灵活的可以通过参数来控制的函数

As we’ve seen, the jQuery() function can be used to do the following:

就像我们看到的,jQuery包含了一下的使用方式

Select and wrap DOM elements to operate upon 选择DOM元素包来进行操作

Serve as a namespace for global utility functions 充当全局命名空间

Create DOM elements from HTML markup 根据HTML标签创建DOM元素

Establish code to be executed when the DOM is ready for manipulation ready事件能在页面DOM树加载完成后执行

jQuery behaves like a good on-page citizen not only by minimizing it incursion

into the global JavaScript namespace, but also by providing an official means to

reduce that minimal incursion in circumstances when a name collision might still

occur, namely when another library such as Prototype requires use of the $ name.

jQuery就像一个守法的公民,不会破坏全局的javascript命名空间,并且尽量减少命名冲突,即使其他语言也使用$作为关键字

How’s that for being user friendly?

You can obtain the latest version of jQuery from the jQuery site at http://

jquery.com/. The version of jQuery that the code in this book was tested against

(version 1.2.1) is included as part of the downloadable code.

In the chapters that follow, we’ll explore all that jQuery has to offer us as page

authors of Rich Internet Applications. We’ll begin our tour in the next chapter as

we bring our pages to life via DOM manipulation.

你能获取最新版本的jQueryhttp://jquery.com/ 版本1.2.1在本书中也不断测试过,还有部分代码可以下载

在下一章中,我们研究jauery提供的福客户端方法,我们通过操作DOM元素来操作页面的研究会在下一个章节中进行

 

posted @ 2009-07-12 15:53  laolaowhn  阅读(1900)  评论(0编辑  收藏  举报