15条给开发者的强大的jQuery使用窍门

原文:
15 Powerful jQuery Tips and Tricks for Developers

http://tutorialzine.com/2011/06/15-powerful-jquery-tips-and-tricks-for-developers/

1. 优化你的选择器用法

$('li[data-selected="true"] a')	// Fancy, but slow
$('li.selected a')	// Better
$('#elem')	// Best
var buttons = $('#navigation a.button');

// Some prefer prefixing their jQuery variables with $:
var $buttons = $('#navigation a.button');
$('a.button:animated');	// Does not use querySelectorAll()
$('a.button').filter(':animated');	// Uses it

2. 对象遍历方法

// Selecting all the navigation buttons:
var buttons = $('#navigation a.button');

// We can loop though the collection:
for(var i=0;i<buttons.length;i++){
    console.log(buttons[i]);	// A DOM element, not a jQuery object
}

// We can even slice it:
var firstFour = buttons.slice(0,4);

3. 选择器属性

$('#container li:first-child').selector    // #container li:first-child
$('#container li').filter(':first-child').selector    // #container li.filter(:first-child)

4. 创建jQuery对象

var container = $([]);
container.add(another_element);

5. ajax的全局配置,今天第一次看到,哈

// ajaxSetup is useful for setting general defaults:
$.ajaxSetup({
    url			: '/ajax/',
    dataType	: 'json'
});

$.ajaxStart(function(){
    showIndicator();
    disableButtons();
});

$.ajaxComplete(function(){
    hideIndicator();
    enableButtons();
});

/*
    // Additional methods you can use:
    $.ajaxStop();
    $.ajaxError();
    $.ajaxSuccess();
    $.ajaxSend();
*/

6. 是jQuery操作html5的data属性

<div id="d1" data-role="page" data-last-value="43" data-hidden="true"
    data-options='{"name":"John"}'>
</div>

操作方法:

$("#d1").data("role");			// "page"
$("#d1").data("lastValue");		// 43
$("#d1").data("hidden");		// true;
$("#d1").data("options").name;	// "John";

7. 文件存储插件

$.jStorage jQuery plugin:

// Check if "key" exists in the storage
var value = $.jStorage.get("key");
if(!value){
    // if not - load the data from the server
 	value = load_data_from_server();
 	// and save it
    $.jStorage.set("key",value);
}

// Use value

via:http://www.4wei.cn/archives/1002224