1.當(dāng)document文檔就緒時(shí)執(zhí)行JavaScript代碼。
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// Different ways to achieve the Document Ready event
// With jQuery
$(document).ready(function(){ /* ... */});
// Short jQuery
$(function(){ /* ... */});
// Without jQuery (doesn't work in older IE versions)
document.addEventListener('DOMContentLoaded',function(){
// Your code goes here
});
// The Trickshot (works everywhere):
r(function(){
alert('DOM Ready!');
})
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
</script>
2.使用route反症。
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var route = {
_routes : {}, // The routes will be stored here
add : function(url, action){
this._routes[url] = action;
},
run : function(){
jQuery.each(this._routes, function(pattern){
if(location.href.match(pattern)){
// "this" points to the function to be executed
this();
}
});
}
}
// Will execute only on this page:
route.add('002.html', function(){
alert('Hello there!')
});
route.add('products.html', function(){
alert("this won't be executed :(")
});
// You can even use regex-es:
route.add('.*.html', function(){
alert('This is using a regex!')
});
route.run();
</script>
3.使用JavaScript中的AND技巧。
使用&&操作符的特點(diǎn)是如果操作符左邊的表達(dá)式是false一膨,那么它就不會(huì)再判斷操作符右邊的表達(dá)式了诞仓。所以:
// Instead of writing this:
if($('#elem').length){
// do something
}
// You can write this:
$('#elem').length && log("doing something");
4. is()方法比你想象的更為強(qiáng)大。
下面舉幾個(gè)例子赁温,我們先寫一個(gè)id為elem的div肛宋。js代碼如下:
// First, cache the element into a variable:
var elem = $('#elem');
// Is this a div?
elem.is('div') && log("it's a div");
// Does it have the bigbox class?
elem.is('.bigbox') && log("it has the bigbox class!");
// Is it visible? (we are hiding it in this example)
elem.is(':not(:visible)') && log("it is hidden!");
// Animating
elem.animate({'width':200},1);
// is it animated?
elem.is(':animated') && log("it is animated!");
其中判斷是否為動(dòng)畫(huà)我覺(jué)得非常不錯(cuò)。
5.判斷你的網(wǎng)頁(yè)一共有多少元素束世。
通過(guò)使用$("*").length屬性可以判斷網(wǎng)頁(yè)的元素?cái)?shù)量。
// How many elements does your page have?
log('This page has ' + $('*').length + ' elements!');
6.使用length()屬性很笨重床玻,下面我們使用exist()方法毁涉。
/ Old way
log($('#elem').length == 1 ? "exists!" : "doesn't exist!");
// Trickshot:
jQuery.fn.exists = function(){ return this.length > 0; }
log($('#elem').exists() ? "exists!" : "doesn't exist!");
7.jQuery方法$()實(shí)際上是擁有兩個(gè)參數(shù)的,你知道第二個(gè)參數(shù)的作用嗎锈死?
// Select an element. The second argument is context to limit the search
// You can use a selector, jQuery object or dom element
$('li','#firstList').each(function(){
log($(this).html());
});
log('-----');
// Create an element. The second argument is an
// object with jQuery methods to be called
var div = $('<div>',{
"class": "bigBlue",
"css": {
"background-color":"purple"
},
"width" : 20,
"height": 20,
"animate" : { // You can use any jQuery method as a property!
"width": 200,
"height":50
}
});
div.appendTo('#result');
8.使用jQuery我們可以判斷一個(gè)鏈接是否是外部的贫堰,并來(lái)添加一個(gè)icon在非外部鏈接中,且確定打開(kāi)方式待牵。
這里用到了hostname屬性其屏。
<ul id="links">
<li><a href="007.html">The previous tip</a></li>
<li><a href="./009.html">The next tip</a></li>
<li><a >Google</a></li>
</ul>
// Loop through all the links
$('#links a').each(function(){
if(this.hostname != location.hostname){
// The link is external
$(this).append('<img src="assets/img/external.png" />')
.attr('target','_blank');
}
});
9.jQuery中的end()方法可以使你的jQuery鏈更加高效。
<ul id="meals"> <li> <ul class="breakfast"> <li class="eggs">No</li> <li class="toast">No</li> <li class="juice">No</li> </ul> </li> </ul>
// Here is how it is used:
var breakfast = $('#meals .breakfast');
breakfast.find('.eggs').text('Yes')
.end() // back to breakfast
.find('.toast').text('Yes')
.end()
.find('.juice').toggleClass('juice coffee').text('Yes');
breakfast.find('li').each(function(){
log(this.className + ': ' + this.textContent)
});
10.也許你希望你的web 應(yīng)用感覺(jué)更像原生的缨该,那么你可以阻止contextmenu默認(rèn)事件偎行。
<script>
// Prevent right clicking on this page
$(function(){
$(document).on("contextmenu",function(e){
e.preventDefault();
});
});
</script>
11.一些站點(diǎn)可能會(huì)使你的網(wǎng)頁(yè)在一個(gè)bar下面,即我們所看到在下面的網(wǎng)頁(yè)是iframe標(biāo)簽中的贰拿,我們可以這樣解決蛤袒。
// Here is how it is used:
if(window != window.top){
window.top.location = window.location;
}
else{
alert('This page is not displayed in a frame. Open 011.html to see it in action.');
}
12.你的內(nèi)聯(lián)樣式表并不是被設(shè)置為不可改變的,如下:
// Make the stylesheet visible and editable
$('#regular-style-block').css({'display':'block', 'white-space':'pre'})
.attr('contentEditable',true);
這樣即可改變內(nèi)聯(lián)樣式了膨更。
13.有時(shí)候我們不希望網(wǎng)頁(yè)的某一部分內(nèi)容被選擇比如復(fù)制粘貼這種事情妙真,我們可以這么做:
<p class="descr">In certain situations you might want to prevent text on the page from being selectable. Try selecting this text and hit view source to see how it is done.</p>
<script>
// Prevent text from being selected
$(function(){
$('p.descr').attr('unselectable', 'on')
.css('user-select', 'none')
.on('selectstart', false);
});
</script>
這樣,內(nèi)容就不能被選擇啦荚守。
14.從CDN中引入jQuery珍德,這樣的方法可以提高我們網(wǎng)站的性能,并且引入最新的版本也是一個(gè)不錯(cuò)的主意矗漾。
下面會(huì)介紹四種不同的方法锈候。
<!-- Case 1 - requesting jQuery from the official CDN -->
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<!-- Case 2 - requesting jQuery from Google's CDN (notice the protocol) -->
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->
<!-- Case 3 - requesting the latest minor 1.8.x version (only cached for an hour) -->
<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10/jquery.min.js"></script> -->
<!-- Case 4 - requesting the absolute latest jQuery version (use with caution) -->
<!-- <script src="http://code.jquery.com/jquery.min.js"></script> -->
15.保證最小的DOM操作。
我們知道js操作DOM是非常浪費(fèi)資源的缩功,我們可以看看下面的例子晴及。
CODE
// Bad
//var elem = $('#elem');
//for(var i = 0; i < 100; i++){
// elem.append('<li>element '+i+'</li>');
//}
// Good
var elem = $('#elem'),
arr = [];
for(var i = 0; i < 100; i++){
arr.push('<li>element '+i+'</li>');
}
elem.append(arr.join(''));
16.更方便的分解URL。
也許你會(huì)使用正則表達(dá)式來(lái)解析URL,但這絕對(duì)不是一種好的方法虑稼,我們可以借用a標(biāo)簽來(lái)實(shí)現(xiàn)它琳钉。
// You want to parse this address into parts:
var url = 'http://tutorialzine.com/books/jquery-trickshots?trick=12#comments';
// The trickshot:
var a = $('<a>',{ href: url });
log('Host name: ' + a.prop('hostname'));
log('Path: ' + a.prop('pathname'));
log('Query: ' + a.prop('search'));
log('Protocol: ' + a.prop('protocol'));
log('Hash: ' + a.prop('hash'));
17.不要害怕使用vanilla.js。
jQuery背負(fù)的太多蛛倦,這便是原因歌懒,你可以用一般的js。
// Print the IDs of all LI items
$('#colors li').each(function(){
// Access the ID directly, instead
// of using jQuery's $(this).attr('id')
log(this.id);
});
18.最優(yōu)化你的選擇器
// Let's try some benchmarks!
var iterations = 10000, i;
timer('Fancy');
for(i=0; i < iterations; i++){
// This falls back to a SLOW JavaScript dom traversal
$('#peanutButter div:first');
}
timer_result('Fancy');
timer('Parent-child');
for(i=0; i < iterations; i++){
// Better, but still slow
$('#peanutButter div');
}
timer_result('Parent-child');
timer('Parent-child by class');
for(i=0; i < iterations; i++){
// Some browsers are a bit faster on this one
$('#peanutButter .jellyTime')
19.緩存你的selector溯壶。
// Bad:
// $('#pancakes li').eq(0).remove();
// $('#pancakes li').eq(1).remove();
// $('#pancakes li').eq(2).remove();
// Good:
var pancakes = $('#pancakes li');
pancakes.eq(0).remove();
pancakes.eq(1).remove();
pancakes.eq(2).remove();
// Alternatively:
// pancakes.eq(0).remove().end()
// .eq(1).remove().end()
// .eq(2).remove().end();
20.對(duì)于重復(fù)的函數(shù)只定義一次
如果你追求代碼的更高性能及皂,那么當(dāng)你設(shè)置事件監(jiān)聽(tīng)程序時(shí)必須小心,只定義一次函數(shù)然后把它的名字作為事件處理程序傳遞是不錯(cuò)的方法且改。
$(document).ready(function(){
function showMenu(){
alert('Showing menu!');
// Doing something complex here
}
$('#menuButton').click(showMenu);
$('#menuLink').click(showMenu);
});
21.像對(duì)待數(shù)組一樣地對(duì)待jQuery對(duì)象
由于jQuery對(duì)象有index值和長(zhǎng)度验烧,所以這意味著我們可以把對(duì)象當(dāng)作普通的數(shù)組對(duì)待。這樣也會(huì)有更好地性能又跛。
var arr = $('li'),
iterations = 100000;
timer('Native Loop');
for(var z=0;z<iterations;z++){
var length = arr.length;
for(var i=0; i < length; i++){
arr[i];
}
}
timer_result('Native Loop');
timer('jQuery Each');
for(z=0;z<iterations;z++){
arr.each(function(i, val) {
this;
});
}
timer_result('jQuery Each');
22.當(dāng)做復(fù)雜的修改時(shí)要分離元素碍拆。
修改一個(gè)dom元素要求網(wǎng)頁(yè)重繪,這個(gè)代價(jià)是高昂的慨蓝,所以如果你想要再提高性能感混,就可以嘗試著當(dāng)對(duì)一個(gè)元素進(jìn)行大量修改時(shí)先從頁(yè)面中分離這個(gè)元素,修改完之后再添加到頁(yè)面礼烈。
// Modifying in place
var elem = $('#elem');
timer('In place');
for(i=0; i < iterations; i++){
elem.width(Math.round(100*Math.random()));
elem.height(Math.round(100*Math.random()));
}
timer_result('In place');
var parent = elem.parent();
// Detaching first
timer('Detached');
elem.detach();
for(i=0; i < iterations; i++){
elem.width(Math.round(100*Math.random()));
elem.height(Math.round(100*Math.random()));
}
elem.appendTo(parent);
timer_result('Detached');
23.不要一直等待load事件弧满。
我們已經(jīng)習(xí)慣了把我們所有的代碼都放在ready的事件處理程序中,但是此熬,如果你的html頁(yè)面很龐大庭呜,decument ready恐怕會(huì)被延遲了,所以對(duì)于一些我們不希望ready后才可以觸發(fā)的事件可以放在html的head元素中犀忱。
<script>
// jQuery is loaded at this point. We can use
// event delegation right away to bind events
// even before $(document).ready:
$(document).on('click', '#clickMe', function(){
alert('Hit view source and see how this is made');
});
$(document).ready(function(){
// This is where you would usually bind event handlers,
// but as we are using delegation, there is no need to.
// $('#clickMe').click(function(){ alert('Hey!'); });
});
// Note: You should place your script tags at the bottom of the page.
// I have included them in the head only to demonstrate that we can bind
// events before document ready and before the elements are created.
</script>
24.當(dāng)使用js給多個(gè)元素添加樣式時(shí)更好的做法是創(chuàng)建一個(gè)style元素疟赊。
我們之前提到過(guò),操作dom是非常慢的峡碉,所以當(dāng)添加多個(gè)元素的樣式時(shí)創(chuàng)建一個(gè)style元素并添加到document中是更好的做法近哟。
<ul id="testList">
<li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li> <li>Item</li>
</ul>
var style = $('<style>');
// Try commenting out this line, or change the color:
style.text('#testList li{ color:red;}');
// Placing it before the result section so it affects the elements
style.prependTo('#result');
25.給html元素分配一個(gè)名為JS的class。
現(xiàn)代的web apps非常的依賴js鲫寄,這里的一個(gè)技巧就是只有當(dāng)js可用時(shí)才能顯示特定的元素吉执。看下面的代碼地来。
$(document).ready(function(){
$('html').addClass('JS');
});
html.JS #message { display:block; }
#message {display:none;}
這樣戳玫,只有js可用的時(shí)候id為message的元素才會(huì)顯示;如果不支持js未斑,則該元素不會(huì)顯示咕宿。
26.監(jiān)聽(tīng)不存在的元素上的事件。
jQuery擁有一個(gè)先進(jìn)的事件處理機(jī)制,通過(guò)on()方法可以監(jiān)聽(tīng)還不存在的事件府阀。 這是因?yàn)閛n方法可以傳遞一個(gè)元素的子元素選擇器作為參數(shù)缆镣。看下面的例子:
<ul id="testList"> <li>Old</li> <li>Old</li> <li>Old</li> <li>Old</li> </ul>
var list = $('#testList');
// Binding an event on the list, but listening for events on the li items:
list.on('click','li',function(){
$(this).remove();
});
// This allows us to create li elements at a later time,
// while keeping the functionality in the event listener
list.append('<li>New item (click me!)</li>');
這樣试浙,即使li是后創(chuàng)建的董瞻,也可以通過(guò)on()方法來(lái)監(jiān)聽(tīng)。
27.只使用一次事件監(jiān)聽(tīng)田巴。
有時(shí)钠糊,我們只需要綁定只運(yùn)行一次的事件處理程序。那么one()方法是一個(gè)不錯(cuò)的選擇壹哺,通過(guò)它你就可以高枕無(wú)憂了抄伍。
<button id="press">Press me!</ul>
var press = $('#press');
// There is a method that does exactly that, the one():
press.one('click',function(){
alert('This alert will pop up only once');
});
// What this method does, is call on() behind the scenes,
// with a 1 as the last argument:
// press.on('click',null,null,function(){alert('I am the one and only!');}, 1);
28.模擬觸發(fā)事件。
我們可以通過(guò)使用trigger模擬觸發(fā)一個(gè)click事件管宵。
<button id="press">Press me!</ul>
var press = $('#press');
// Just a regular event listener:
press.on('click',function(e, how){
how = how || '';
alert('The buton was clicked ' + how + '!');
});
// Trigger the click event
press.trigger('click');
// Trigger it with an argument
press.trigger('click',['fast']);
29.使用觸摸事件逝慧。
使用觸摸事件和相關(guān)的鼠標(biāo)事件并沒(méi)有太多不同,但是你得有一個(gè)方便的移動(dòng)設(shè)備來(lái)測(cè)試會(huì)更好啄糙。看下面這個(gè)例子云稚。
// Define some variables
var ball = $('<div id="ball"></div>').appendTo('body'),
startPosition = {}, elementPosition = {};
// Listen for mouse and touch events
ball.on('mousedown touchstart',function(e){
e.preventDefault();
// Normalizing the touch event object
e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
// Recording current positions
startPosition = {x: e.pageX, y: e.pageY};
elementPosition = {x: ball.offset().left, y: ball.offset().top};
// These event listeners will be removed later
ball.on('mousemove.rem touchmove.rem',function(e){
e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
ball.css({
top:elementPosition.y + (e.pageY - startPosition.y),
left: elementPosition.x + (e.pageX - startPosition.x),
});
});
});
ball.on('mouseup touchend',function(){
// Removing the heavy *move listeners
ball.off('.rem');
});
30.更好地使用on()/off()方法隧饼。
在jQuery1.7版本時(shí)對(duì)事件處理進(jìn)行了簡(jiǎn)化,看看下面的例子吧静陈。
<div id="holder"> <button id="button1">1</button> <button id="button2">2</button> <button id="button3">3</button> <button id="button4">4</button> <button id="clear" style="float: right;">Clear</button> </div>
// Lets cache some selectors
var button1 = $('#button1'),
button2 = $('#button2'),
button3 = $('#button3'),
button4 = $('#button4'),
clear = $('#clear'),
holder = $('#holder');
// Case 1: Direct event handling
button1.on('click',function(){
log('Click');
});
// Case 2: Direct event handling of multiple events
button2.on('mouseenter mouseleave',function(){
log('In/Out');
});
// Case 3: Data passing
button3.on('click', Math.round(Math.random()*20), function(e){
// This will print the same number over and over again,
// as the random number above is generated only once:
log('Random number: ' + e.data);
});
// Case 4: Events with a namespace
button4.on('click.temp', function(e){
log('Temp event!');
});
button2.on('click.temp', function(e){
log('Temp event!');
});
// Case 5: Using event delegation
$('#holder').on('click', '#clear', function(){
log.clear();
});
// Case 6: Passing an event map
var t; // timer
clear.on({
'mousedown':function(){
t = new Date();
},
'mouseup':function(){
if(new Date() - t > 1000){
// The button has been held pressed
// for more than a second. Turn off
// the temp events
$('button').off('.temp');
alert('The .temp events were cleared!');
}
}
});
31.更快地阻止默認(rèn)事件行為燕雁。
我們知道js中可以使用preventDefault()方法來(lái)阻止默認(rèn)行為,但是jQuery對(duì)此提供了更簡(jiǎn)單的方法鲸拥。如下:
<a id="goToGoogle">Go To Google</a>
$('#goToGoogle').click(false);
32.使用event.result鏈接多個(gè)事件處理程序拐格。
對(duì)一個(gè)元素綁定多個(gè)事件處理程序并不常見(jiàn),而使用event.result更可以將多個(gè)事件處理程序聯(lián)系起來(lái)刑赶∧笞牵看下面的例子。
<button id="press">點(diǎn)擊</button>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var press = $('#press');
press.on('click',function(){
return 'Hip';
});
// The second event listener has access
// to what was returned from the first
press.on('click',function(e){
console.log(e.result + ' Hop!');
});
</script>
這樣撞叨,控制臺(tái)會(huì)輸出Hip Hop!
33.創(chuàng)建你自己習(xí)慣的事件金踪。
你可以使用on()方法創(chuàng)建自己喜歡的事件名稱,然后通過(guò)trigger來(lái)觸發(fā)牵敷。舉例如下:
<button id="button1">Jump</button> <button id="button2">Punch</button> <button id="button3">Click</button> <button id="clear" style="float: right;">Clear</button> <div id="eventDiv"></div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
var button1 = $('#button1'),
button2 = $('#button2'),
button3 = $('#button3'),
clear = $('#clear'),
div = $('#eventDiv');
div.on({
jump : function(){
alert('Jumped!');
},
punch : function(e,data){
alert('Punched '+data+'!');
},
click : function(){
alert('Simulated click!');
}
});
button1.click(function(){
div.trigger('jump');
});
button2.click(function(){
// Pass data along with the event
div.trigger('punch',['hard']);
});
button3.click(function(){
div.trigger('click');
});
clear.click(function(){
//some clear code
});
</script>
34.在下載文件旁顯示文件大小胡岔。
你知道如何在不下載一個(gè)文件的情況下通過(guò)發(fā)送一個(gè)ajax請(qǐng)求頭得到一個(gè)文件的大小嗎? 使用jQuery就很容易枷餐。
<a href="001.html" class="fetchSize">First Trickshot</a> <br />
<a href="034.html" class="fetchSize">This Trickshot</a> <br />
<a href="assets/img/ball.png" class="fetchSize">Ball.png</a> <br />
// Loop all .fetchSize links
$('a.fetchSize').each(function(){
// Issue an AJAX HEAD request for each one
var link = this;
$.ajax({
type : 'HEAD',
url : link.href,
complete : function(xhr){
// Append the filesize to each
$(link).append(' (' + humanize(xhr.getResponseHeader('Content-Length')) + ')');
}
});
});
function humanize(size){
var units = ['bytes','KB','MB','GB','TB','PB'];
var ord = Math.floor( Math.log(size) / Math.log(1024) );
ord = Math.min( Math.max(0,ord), units.length-1);
var s = Math.round((size / Math.pow(1024,ord))*100)/100;
return s + ' ' + units[ord];
}
注意:這個(gè)例子如何我們直接使用瀏覽器是沒(méi)法得到的靶瘸,必須使用本地的web服務(wù)器打開(kāi)運(yùn)行才可以。
35.使用延遲簡(jiǎn)化你的Ajax請(qǐng)求
延遲(deferreds)是一個(gè)強(qiáng)大的工具。jQuery對(duì)于每一個(gè)Ajax請(qǐng)求都會(huì)返回一個(gè)deferred對(duì)象怨咪。 deferred.done()方法接受一個(gè)或多個(gè)參數(shù)屋剑,所有這些都參數(shù)可以是一個(gè)單一的函數(shù)或一個(gè)函數(shù)數(shù)組。當(dāng)Deferred(延遲)解決時(shí)惊暴,doneCallbacks被調(diào)用饼丘。回調(diào)是依照他們添加的順序執(zhí)行辽话。一旦deferred.done()返回Deferred(延遲)對(duì)象肄鸽,Deferred(延遲)可以鏈接其它的延遲對(duì)象,包括增加額外的.done()方法油啤。下面這樣就會(huì)使你的代碼更易讀:
// This is equivalent to passing a callback as the
// second argument (executed on success):
$.get('assets/misc/1.json').done(function(r){
log(r.message);
});
// Requesting a file that does not exist. This will trigger
// the failure response. To handle it, you would normally have to
// use the full $.ajax method and pass it as a failure callback,
// but with deferreds you can can simply use the fail method:
$.get('assets/misc/non-existing.json').fail(function(r){
log('Oops! The second ajax request was "' + r.statusText + '" (error ' + r.status + ')!');
});
36.平行的運(yùn)行多個(gè)Ajax請(qǐng)求典徘。
當(dāng)我們需要發(fā)送多個(gè)Ajax請(qǐng)求是,相反于等待一個(gè)發(fā)送結(jié)束再發(fā)送下一個(gè)益咬,我們可以平行地發(fā)送來(lái)加速Ajax請(qǐng)求發(fā)送逮诲。
// The trick is in the $.when() function:
$.when($.get('assets/misc/1.json'), $.get('assets/misc/2.json')).then(function(r1, r2){
log(r1[0].message + " " + r2[0].message);
});
37.通過(guò)jQuery獲得ip
我們不僅可以在電腦上ping到一個(gè)網(wǎng)站的ip,也可以通過(guò)jQuery得到幽告。
$.get('http://jsonip.com/', function(r){ log(r.ip); });
// For older browsers, which don't support CORS
// $.getJSON('http://jsonip.com/?callback=?', function(r){ log(r.ip); });
38.使用最簡(jiǎn)單的ajax請(qǐng)求
jQuery(使用ajax)提供了一個(gè)速記的方法來(lái)快速下載內(nèi)容并添加在一個(gè)元素中梅鹦。
<p class="content"></p> <p class="content"></p>
var contentDivs = $('.content');
// Fetch the contents of a text file:
contentDivs.eq(0).load('1.txt');
// Fetch the contents of a HTML file, and display a specific element:
contentDivs.eq(1).load('1.html #header');
39.序列化對(duì)象
jQuery提供了一個(gè)方法序列化表單值和一般的對(duì)象成為URL編碼文本字符串。這樣冗锁,我們就可以把序列化的值傳給ajax()作為url的參數(shù)齐唆,輕松使用ajax()提交表單了。
<form action="">
First name: <input type="text" name="FirstName" value="Bill" /><br />
Last name: <input type="text" name="LastName" value="Gates" /><br />
</form>
// Turn all form fields into a URL friendly key/value string.
// This can be passed as argument of AJAX requests, or URLs.
$(document).ready(function(){
console.log($("form").serialize()); // FirstName=Bill&LastName=Gates
});
// You can also encode your own objects with the $.param method:
log($.param({'pet':'cat', 'name':'snowbell'}));
40.使用jQuery上傳二進(jìn)制文件
現(xiàn)在的瀏覽器都支持FormData API冻河,這可以是我們很輕松的通過(guò)ajax來(lái)發(fā)送數(shù)據(jù)箍邮。 并將之結(jié)合HTML5中的File API,我們就可以上傳二進(jìn)制文件了叨叙。
// The file input field
var fileInput = $('input[type=file]'),
button = $('#upload');
button.on('click', function(){
// Access the files property, which holds
// an array with the selected files
var files = fileInput.prop('files');
// No file was chosen!
if(files.length == 0) {
alert('Please choose a file to upload!');
return false;
}
// Create a new FormData object
var fd = new FormData();
fd.append('file', files[0]);
// Upload the file to assets/php/upload.php. Open that file in a text
// editor to get a better idea of how it works.
$.ajax({
url: './assets/php/upload.php',
data: fd,
contentType:false, // This will make the browser use the multipart/formdata encoding, which is required for transferring binary data.
processData:false, // jQuery shouldn't do any processsing on the data - the browser will handle this when it sees we are passing a formdata object.
type:'POST',
success: function(m){
log(m);
}
});
});
41.使用Facebook的圖表
我們可以引入facebook中的一個(gè)很強(qiáng)大的API來(lái)是我們的app更加社交化锭弊。下面是一個(gè)簡(jiǎn)單的例子:
CODE
// Fetch the publicly accessible data on Tutorialzine's Page
var api = 'http://graph.facebook.com/Tutorialzine/?callback=?',
holder = $('#fbdata');
$.getJSON(api, function(r){
// This will always give the current picture
holder.append('<img src="http://graph.facebook.com/Tutorialzine/picture/?type=large">');
holder.append('<p>'+ r.about +'</p>')
holder.append('<a href="'+ r.website +'">'+ r.website +'</a>');
});
42.獲取天氣信息
Open Weather Map提供了免費(fèi)的天氣信息,我們可以通過(guò)使用它們的JSON API來(lái)獲取數(shù)據(jù)擂错。簡(jiǎn)單的例子如下:
// Request weather data:
var api = 'http://openweathermap.org/data/2.1/find/name?q=paris,france&callback=?';
$.getJSON(api, function(r){
// This will always give the current picture
log(r.list[0].name + ', ' + r.list[0].sys.country);
log(r.list[0].main);
// Temperatures are in kelvin, subtract 273.15 to convert to Celsius,
});
43. 獲取你的最近的湯博樂(lè)(Tumblr)內(nèi)容
現(xiàn)在非常流行的湯博樂(lè)博客服務(wù)提供了簡(jiǎn)單的方法使用JSON api味滞, 這樣我們可以使用它來(lái)獲取任何博客內(nèi)容,下面是使用的方法钮呀。
<div id="post"></div>
// Define variables
var blog = 'minimaldesks.tumblr.com',
api = 'http://' + blog + '/api/read/json?callback=?',
post = $('#post');
$.getJSON(api, function(r){
log('Blog title: ' + r.tumblelog.title);
log('Description: ' + r.tumblelog.description);
// If this post has a photo, show it
if(r.posts[0]['photo-url-250']){
post.append('<img src="' + r.posts[0]['photo-url-250'] + '" />');
}
else{
log('Latest post: ' + r.posts[0]['regular-title']);
}
});
44.通過(guò)IP地址獲得地理位置
有很多在線服務(wù)可以告訴我們IP地址所在的城市和國(guó)家桃犬,下面我們先ping到百度的IP地址,然后獲取其地理位置:
// Define variables
var ip = '119.75.218.70', // you can optionally put an ip address here
api = 'http://freegeoip.net/json/' + ip + '?callback=?';
$.getJSON(api, function(r){
console.log('How is the weather in ' + r.city + ', ' + r.country_name + '?');
}); //How is the weather in Beijing, China?
45.使用YQL來(lái)爬網(wǎng)站
YQL對(duì)JavaScript開(kāi)發(fā)者來(lái)說(shuō)有無(wú)限的API行楞,下面的例子是我們?nèi)绾问褂盟鼇?lái)獲取并解析其他站點(diǎn)的HTML攒暇。
CODE
// Define variables
var query = 'select * from data.html.cssselect where url="http://www.chucknorrisfacts.com/chuck-norris-top-50-facts" and css=".field-content a"';
var yqlAPI = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + ' &format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
$.getJSON(yqlAPI, function(r){
log('Chuck Norris Facts:');
$.each(r.query.results.results.a, function(){
log('----------');
log(this.content);
});
});
46.使用全局的Ajax方法
我們可以通過(guò)ajax的全局方法來(lái)簡(jiǎn)化web app中處理的ajax請(qǐng)求。
CODE
// Create an indicator that would be shown whenever an AJAX request occurs:
var preloader = $('<div>',{ 'class':'preloader' }).appendTo('body');
var doc = $(document);
// Show the preloader whenever you are making an AJAX request:
doc.ajaxStart(function(){
preloader.fadeIn();
});
// Hide it when the ajax request finishes
doc.ajaxComplete(function(){
// Keep it visible for 0.8 seconds after the request completes
preloader.delay(800).fadeOut();
});
// It will show automatically every time you do an AJAX request:
$.get('assets/misc/1.json');
47. 學(xué)會(huì)愛(ài)上console吧子房。
我們的瀏覽器給了我們一系列有用的方法使用來(lái)調(diào)試代碼形用,找出bug就轧,下面就是一個(gè)例子,打開(kāi)console看看吧田度。
// The simple case. Use this instead of alert():
console.log('This is a console message!');
// It supports embedding of variables as well:
var a = 'morning', b = 'Miss';
console.log('Good %s %s! How are you feeling today?', a, b);
// Interactively browse the properties of a method (similar to console.log):
console.dir(window);
// Information message (in webkit it looks like console.log)
console.info('Everything is OK');
// Warning message
console.warn('Something may be wrong');
// Error message (will print a stack trace)
console.error('Ooops. That was bad.');
// Counting things
for(var i = 0; i<20; i++){
console.count('Counter Name');
}
// Starts a collapsable group of log messages
console.group("Preflight check");
console.info('Fuel is OK');
console.info('Temperature is normal');
console.error('Wings are missing');
console.groupEnd()
// Timing things
console.time('The million-dollar loop')
var dollars = 0;
for(var i=0;i<100000; i++){
dollars+=10;
}
console.timeEnd('The million-dollar loop');
// Profiling code (it will show up in your console's Profile tab)
console.profile('My app performance');
var arr = [];
$.each([0,1,2,3,4,5,6,7,8,9],function(){
arr.push(this+1);
});
console.profileEnd('My app performance');
48.把代碼轉(zhuǎn)化為插件以提高重用率妒御。
如果有一些代碼你總是在不同的項(xiàng)目之間復(fù)制粘貼,你就可以考慮著把它轉(zhuǎn)化成一個(gè)插件了镇饺。下面的例子就是這樣乎莉。
<input id="testInput" placeholder="YourName"/>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// Define the placeholder plugin
$.fn.placeholder = function(){
if ('placeholder' in document.createElement('input')){
// This browser already supports placeholders.
// Nothing to do here.
return this;
}
this.each(function(){
var input = $(this);
input.on('focus', function(){
if(input.val() == input.attr('placeholder')){
input.val('');
}
}).on('blur', function(){
if(input.val() == ''){
input.val(input.attr('placeholder'));
}
});
// Show the placeholder on load
input.trigger('blur');
});
return this;
};
// And here is how to use it:
$('#testInput').placeholder();
49.使用匿名函數(shù)來(lái)產(chǎn)生一個(gè)獨(dú)立的代碼塊
定義全局變量和函數(shù)是一種代碼很粗糙的行為,更好的方式是通過(guò)使用匿名函數(shù)使你的代碼獨(dú)立于塊之中奸笤⊥锟校看下面的例子:
// Isolating a block of code:
(function($){
// Declare a variable. It will only be visible in this block.
var c = 1;
// Define a simple plugin
$.fn.count = function(){
// Increment and log the counter
log(c++);
return this;
};
})(jQuery);
// The c variable is only visible for the plugin and will keep
// its value between invocations:
$(document).count();
$('body').count().count();
50. 用extend融合對(duì)象
當(dāng)提到從多個(gè)項(xiàng)目到一個(gè)項(xiàng)目結(jié)合屬性時(shí),你最好的猜測(cè)就是擴(kuò)展方法监右。
// Combine properties (useful in plugins).
// The defaults are passed as the first argument.
var supplied = { height: 400 };
var options = $.extend({
color : 'blue',
width : 200,
height : 150
}, supplied);
log('New options:', options);
// You can also pass more than one object
log('Three parents:', $.extend({a:2}, {b:3}, {c:4}) );
log('-------');
// Cloning objects.
// To clone an object, simply pass an empty one
// as the first argument
var original = {a:123, b:'#fff'};
var clone = $.extend({}, original);
log('Clone:', clone);
log('-------');
// Extending jQuery.
// You can define plugins with extend
$.extend($.fn, {
plugin1: function(){
log('Plugin 1');
return this;
},
plugin2: function(){
log('Plugin 2');
return this;
}
});
$('body').plugin1().plugin2();
log('-------');
// If you pass only one arguments to $.extend,
// it will add the properties to the jQuery object
$.extend({ dontDoThis : 123});
log($.dontDoThis);
log('-------');
// Deep cloning.
// If you have nested objects, you will have to
// pass one additional argument to extend:
var obj1 = { a: 1, b: 2, c: {d: 3} };
var obj2 = { c: {e: 4}, f:5};
// This won't work
// $.extend(obj1, obj2);
// This will
$.extend(true, obj1,obj2);
log('Deep clone:', obj1);