简单实现
Ajax
Ajax couldn't be any easier than it is with jQuery. jQuery has a handful of functions that make the easy stuff really easy and the complex stuff as simple as possible.
A common use of Ajax is to load a chunk of HTML into an area of the page. To do that, simply select the element you need and use the
load()
function. Here's an example that updates some statistics:
$('#stats').load('stats.html');
不会再有比
jQuery
更简单的方法实现
Ajax
了。
jQuery
有很多功能可以使复杂的变为简单,简单的更加简单。一种经常使用的
Ajax
实现是将一大堆
HTML
查到页面的某个区域中去。可以使用
load()
函数轻松的实现。这个例子更新了一些统计数据。
Often, you simply need to pass some parameters to a page on the server. As you'd expect, this is incredibly simple in jQuery, too. You can use choose between
$.post()
and
$.get()
, depending on which method you need. You can pass an optional data object and callback function if you need them. Listing 4 shows a simple example that sends data and uses a callback.
通常,你仅仅是需要向服务器传送一些参数。和你预期的一样,在
jQuery
中会超乎想象的简单。你可以选择
$.post()
或是
$.get()
函数,这取决于你希望使用那种提交方式。如果需要的话,还可以传送一个可选数据和回调函数。
Listing4
展示了一个发送数据并使用回调函数的简单例子。
$.post('save.cgi', {
text: 'my string',
number: 23
}, function() {
alert('Your data has been saved.');
});
If you really want to do some complex Ajax scripting, you need the
$.ajax()
function. You can specify
xml
,
html
,
script
, or
json
, and jQuery automatically prepares the result for your callback function so that you can use it right away. You can also specify
beforeSend
,
error
,
success
, or
complete
callbacks to give the user more feedback about the Ajax experience. In addition, other parameters are available with which you can set the timeout of an Ajax request or the "Last Modified" state of a page. Listing 5 shows an example that retrieves an XML document using some of the parameters that I mentioned.
如果你真的需要制作一些复杂的
Ajax
脚本,你就需要用到
$.ajax()
方法。你可以指定
xml,html,script
或者是
json,jQuery
自动为你准备了一些回调函数,以便你可以马上使用。你同样也可以指定
beforesend
,
error
,
success
或者是
complete
来为用户提供更多的
Ajax
体验。而且,你可以设置请求超时或者是“最近更新”的页面状态的参数。
Listing5
提供了一个使用前面提供的参数取得一个
XML
文档的例子。
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
When you get the XML back in the success callback, you can use jQuery to look through the XML the same way you do with HTML. This makes it easy to work with an XML document and integrate the contents and data into your Web site. Listing 6 shows an expansion on the
success
function that adds a list item to the Web page for each
<item>
element in the XML.
当你使用
success
回调函数取得
XML
,你可以使用
jQuery
像遍历
HTML
一样来遍历
XML
文档。这使得操作
XML
文档并将内容和数据整合到站点中变得相当简单。
Listing6
展示了一种扩展
success
方法来向
XML
页面中的每一个
<item>
元素添加一个
list
元素。
success: function(xml){
$(xml).find('item').each(function(){
var item_text = $(this).text();
$('<li></li>')
.html(item_text)
.appendTo('ol');
});
}
HTML
的动画效果
You can use jQuery to take care of basic animations and effects. At the heart of the animation code is the
animate()
function, which changes any numeric CSS style value over time. For example, you can animate height, width, opacity, or position. You can also specify the speed of the animation, either in milliseconds or in one of the predefined speeds: slow, normal, or fast.
Here's an example that animates the height and width of an element at the same time. Notice that there is no start value -- only the end value. The start values are taken from the current size of the element. I've also attached a callback function.
你可以使用
jQuery
来创建简单的动画效果。动画的核心是
animate
()方法,它通过改变
CSS
的数字实现动画效果。例如,你可以创建关于高度,宽度,透明度或是位置的动画。当然你也可以指定动画的播放速度。
下面是一个同时改变元素对象高度和宽度的动画。注意,这里没有开始值,只有结束值,开始值取决于元素当前的大小。我还加入了一个回调函数。
$('#grow').animate({ height: 500, width: 500 }, "slow", function(){
alert('The element is done growing!');
});
jQuery makes the more common animations easier with built-in functions. You can use
show()
and
hide()
elements, either instantly or at a specified speed. You can also make elements appear and disappear by using
fadeIn()
and
fadeOut()
or
slideDown()
and
slideUp()
, depending on what kind of effect you're looking for. Here's a simple example that slides down a navigation:
$('#nav').slideDown('slow');
jQuery
在内建函数的帮助之下,使得实现更多的常规动画变得更加简单。你可以使用
show
()函数或是
hide
函数使得元素对象立刻或者依照你指定的速度作变化。你同样可以利用
fadein(),fadeout(),slidedown(),sldedown()
函数使元素出现或者消失,这主要取决于你所希望出现的效果。下面是一个简单的导航栏的滑动实例。
jQuery is, perhaps, best at simplifying DOM scripting and event handling. Traversing and manipulating the DOM is easy, and attaching, removing, and calling events is completely natural and much less error prone than doing it by hand.
In essence, jQuery makes it easier to do things that are common with DOM scripting. You can create elements and use the
append()
function to link them to other elements, use
clone()
to duplicate elements, set the contents with
html()
, delete the contents with the
empty()
function, delete the elements altogether with the
remove()
function, and even use the
wrap()
function to wrap the elements with another element.
Several functions are available for changing the contents of the jQuery object itself by traversing the DOM. You can get all the
siblings()
,
parents()
, or
children()
of an element. You can also select the
next()
or
prev()
sibling elements. Perhaps most powerful is the
find()
function, which allows you to use a jQuery selector to search through the descendants of elements in your jQuery object.
These functions become more powerful when used with the
end()
function. This function is like an undo function, going back to the jQuery object you had before you called
find()
or
parents()
or one of the other traversing functions.
When used together with method chaining, these functions allow complex operations to look simple. Listing 7 shows an example in which you find a login form and manipulate several elements around it.
jQuery
或许是简化
DOM
,时间句柄处理的最佳简化方案了。你可以通过
append
()函数建立一个元素与其他元素的关系,使用
clone
()函数复制元素,使用
html()
函数设置它的内容,使用
empty
()函数清空内容,使用
remove
()函数删除绑定在一起的所有元素。甚至是使用
wrap
函数来将一个元素绑定到另一个元素上去。
一些函数通过遍历
DOM
来改变
jQuery
对象的内容。你可以利用
siblings
(),
parents
()或者是
children
()函数来获得相应的元素。你当然也可以通过
next
()或者是
prev
()滑动(查看)元素。或者是用功能更加强大的
find
()函数,它可以让你使用
jQuery
选择器在你的
jQuery
中寻找所有的子元素。
这些函数在于
end
()函数一起使用的时候会变得更加强大。
End
()函数就像一个
undo
(撤销操作)函数,使你可以得到之前用
find
(),
parents
()或者是其他遍历函数得到的元素的前一个元素。
当同时使用函数链的时候,这些函数将会使得复杂的操作变得更加简单。
Listing7
举了个例子,其中你可以看到一个登陆表单并且操作它周围的一些元素。
$('form#login')
// hide all the labels inside the form with the 'optional' class
.find('label.optional').hide().end()
// add a red border to any password fields in the form
.find('input:password').css('border', '1px solid red').end()
// add a submit handler to the form
.submit(function(){
return confirm('Are you sure you want to submit?');
});
Believe it or not, this example is just a single, chained, line of code spread out with whitespace. First, I selected the login form. Then, I found the optional labels inside it, hid them, and called
end()
to go back to the form. I found the password field, made the border red, and again called
end()
to go back to the form. Finally, I added a submit event handler to the form. What's especially interesting about this (besides its obvious brevity) is that jQuery completely optimizes all the query operations, making sure that you don't have to find an element twice when everything is nicely chained together.
Handling common events is as simple as calling a function like
click()
,
submit()
, or
mouseover()
and passing it an event handler function. Additionally, you have the option of assigning a custom event handler using
bind('eventname', function(){})
. You can remove certain events using
unbind('eventname')
or all events with
unbind()
. For a complete list of ways to use these and other functions, check out the jQuery application program interface (API) documentation in the Resources.
不论你相信不相信,这个例子还是一个单行的,像条链子一样,不纯在空格的一段代码。首先,我选择了登陆表单。然后,我找到了里面的选择标签,隐藏掉它,最后调用
end
()函数回到表单元素。又发现了密码输入框,使它的边框变红,然后再调用
end
()函数回到
f
表单元素。最后,我为
form
元素添加了一个提交事件的句柄。
jQuery
完全优化了所有的查询操作,以保证你不需要在所有东西都链接在一起之后还要来查找这个元素第二次。
处理常规的时间很简单,调用像
click
(),
submit
()或者是
mouseover
()函数然后传送(调用)一个事件的句柄函数。除此之外,你还可以选择自己建立时间句柄,通过使用
bind
(‘
eventname
’,
function
()
{}
)。你也可以通过使用
unbind
(‘
eventname
’)解除特定的时间绑定,或者使用
unbind
()解除所有事件。如果需要完整的列表来使用其他函数,请查看
jQuery
的
API
。
释放
jQuery
选择器的潜力!
Often, you select elements by ID, such as
#myid
, or by class name, such as
div.myclass
. However, jQuery has a rather complex and complete selector syntax that allows you to select nearly any combination of elements in a single selector.
jQuery's selector syntax is based heavily on CSS3 and XPath. The more you know about CSS3 and XPath syntax, the better you'll be at using jQuery. For a complete list of jQuery selectors, including CSS and XPath, check out the links in Resources.
CSS3 contains some syntax that not every browser supports, so you don't see it often. However, you can still use CSS3 in jQuery to select elements, because jQuery has its own, custom selector engine. For example, to add a dash inside every empty column of a table, use the
:empty
pseudo-selector:
通常情况下,你会通过使用
div
。
Myclass
这样的类名或者
id
来选择一个元素。然而,
jQuery
拥有一个非常复杂和全面的选择变量,使得你可以选择几乎所有的单个元素,或是一组元素。
jQuery
的选择器变量基于
CSS3
和
Xpath
。你对
CSS3
和
Xpath
的了解将会使得你更好的使用
jQuery
。如果需要
jQuery
选择器的完整列表,请点击
Resource
中的链接。
CSS3
包含了许多现在浏览器还不支持的语法,所以你可能不会很熟悉它。然而,你仍然可以在
jQuery
中使用
CSS3
来选择元素,因为
jQuery
拥有它自己独特的选择器引擎。举个例子,在一个表格中所有空栏中加入破折号,可以使用
empty
伪选择器。
$('td:empty').html('-');
What about finding every element that doesn't have a certain class? CSS3 has a syntax for that, too, using the
:not
pseudo-selector. Here's how you can hide every input that doesn't have a class of
required
:
如何选择不包含特定节点的所有节点?
CSS3
有一个可以使用的语法:使用
not
伪选择器。下面的例子隐藏了所有不包含
required
类的文本输入框。
$('input:not(.required)').hide();
You can also join multiple selectors into one using commas, just as in CSS. Here's a simple example that hides every type of list on the page at the same time:
你也可以使用逗号来加入多重选择,就像使用
CSS
一样。这个例子同时隐藏当前页面中的各种列表。
$('ul, ol, dl').hide();
XPath is a powerful syntax for finding elements in a document. It's a bit different than CSS and lets you do a few things you can't do with CSS. To add a border to the parent element of every check box, you can use XPath's
/..
syntax:
Xpath
在文档中查找节点上功能强大。这和
CSS
有些不同,并且可以完成一些
CSS
无法完成的事情。为每一个多选框的父节点都加上边框,你可以像下面这样使用
Xpath
语句:
$("input:checkbox/..").css('border', '1px solid #777');
jQuery adds extra selectors that aren't available in CSS or XPath, as well. For example, to make a table more readable, you would typically attach a different class name to every odd or even row of the table -- otherwise known as striping the table. Doing this with jQuery is a cinch, thanks to the
:odd
pseudo-selector. This example changes the background of every odd row in tables with a
striped
class:
jQuery
也支持一些在
CSS
和
Xpath
中都不支持的选择器。比如你想让一个表格更具可读性,你通常会每隔一行附加一个样式表。
$('table.striped > tr:odd').css('background', '#999999');
You can see how the power of jQuery selectors can simplify your code. Whatever selection of elements you want to affect, no matter how specific or obscure, you can probably find a way to define them using a single jQuery selector.
强大的
Jquery
选择器可以简化你的代码。不论你要选择的节点是多么的特定或是隐讳,你都会在
jQuery
选择器中找到一种方法。
使用插件扩展
jQuery
Unlike with most software, writing plug-ins for jQuery isn't a huge ordeal with a complex API. In fact, jQuery plug-ins are so easy to write that you might want to write a few to make your code even simpler. Here's the most basic jQuery plug-in you can write:
与大多数软件不同,为
jQuery
开发插件并不会用到复杂的
API
函数。事实上,
jQuery
制作插件非常简单,而且可以使你的代码更加简单。这里给出了一些基本的
jQuery
插件。
$.fn.donothing = function(){
return this;
};
Although simple, this plug-in does require a bit of explanation. First, to add a function to every jQuery object, you must assign it to
$.fn
. Next, this function must return
this
(the jQuery object) so that it doesn't break method chaining.
尽管简单,这个插件还是需要一些解释。首先,为每一个
jQuery
加入一个函数,你必须使用
$.fn
调用他,然后,这个函数必须返回
this
,自由这样,才不会破坏
jQuery
的函数链。
You can easily build on top of this simple example. To write a plug-in to change the background instead of using
css('background')
, you use this:
你可以轻松的使用这个例子。写一个插件,用来改变背景,而不使用
css
(“
background
”),
you use this
:
$.fn.background = function(bg){
return this.css('background', bg);
};
Notice that I could just return the value from
css()
, because it already returns the jQuery object. So, method chaining will still work fine.
I recommend that you use jQuery plug-ins anytime you find that you repeat yourself. For example, you might use a plug-in if you're using the
each()
function to do the same thing over and over.
Because jQuery plug-ins are so easy to write, hundreds of them are available for you to use. jQuery has plug-ins for tabs, rounded corners, slide shows, tool tips, date selectors, and probably anything else you can imagine. For a complete list of plug-ins, check out the Resources.
The most complex and most widely used plug-in is Interface, an animation plug-in that handles sorting, drag-and-drop functionality, complex effects, and other interesting and complex user interfaces (UIs). Interface is to jQuery what Scriptaculous is to Prototype.
Also popular and useful is the Form plug-in, which allows you to easily submit a form in the background using Ajax. This plug-in takes care of the common situation in which you need to hijack the submit event of a form, then find all the different input fields and use them to construct an Ajax call.
你可能注意到,我仅仅是从
css
()返回了一个值,因为它已经返回了一个
jQuery
对象。所以,函数链仍然会工作的很好。
我建议在发现重复的时候使用
jQuery
的插件。举个例子,当你在使用
each
()函数来一遍又一遍的作相同的事情,就应该使用到插件。因为
jQuery
的插件编写相当的简单,你可以使用数以百计的插件。
jQuery
有标签,圆角,滑动显示,工具提示,日期选择,或是其他你可以想得到的其他功能的插件。如果需要
jQuery
的全部插件列表,可以访问如下链接。
使用最广泛也是最复杂的插件是
interface
插件,这是一个动画插件,他可以处理排序,拖放功能,复杂的效果和其他一些复杂但有趣的用户界面。
Interface
对于
jQuery
就好像
Scriptaculous
对
Prototype
一样重要。
同样受欢迎的插件还有
From
,它可以使你轻松的使用
Ajax
的处理表单。这个插件用来劫持表单对象的事件,然后使用不同的输入框建立
Ajax
调用。
I've only scratched the surface of what is possible with jQuery. jQuery is fun to use, because you always learn new tricks and features that seem so natural. jQuery simplifies your JavaScript and Ajax programming completely from the first moment you use it; every time you learn something new, your code gets a bit simpler.
After learning jQuery, I've had a lot more fun programming in the JavaScript language. All the boring stuff is taken care of, so I can focus on coding the juicy stuff. With jQuery, I can barely remember the last time I wrote a
for
loop. I even cringe at the thought of working with other JavaScript libraries. jQuery has honestly and truly changed the way I look at JavaScript programing forever.
我仅仅是学会了
jQuery
的表面上的东西。使用
jQuery
是一件快乐的事情,你会不停的发现学习到新的技巧和特性,而这一切是那么的自然。
jQuery
简化了你的
Javascript
和
Ajax
编程从你使用它的那一刻起。你每学会一些新的东西,你的代码就回变得简单一些。
在学习了
jQuery
之后,我觉得使用
Javascript
语言编程更加有趣。使用
jQuery
,我几乎忘记了最后一次写
for
循环是在什么时候。我甚至不愿意在工作中使用其他
JavaScript
库。
jQuery
永远改变了我对
Javascript
编程方法