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

原文:
15 Powerful jQuery Tips and Tricks for Developers

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

1. 优化你的选择器用法

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

[js]
var buttons = $('#navigation a.button');

// Some prefer prefixing their jQuery variables with $:
var $buttons = $('#navigation a.button');
[/js]

[js]
$('a.button:animated'); // Does not use querySelectorAll()
$('a.button').filter(':animated'); // Uses it
[/js]

2. 对象遍历方法

[js]
// 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);
[/js]

3. 选择器属性

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

4. 创建jQuery对象

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

5. ajax的全局配置,今天第一次看到,哈
[js]
// 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();
*/
[/js]

6. 是jQuery操作html5的data属性

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

操作方法:

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

7. 文件存储插件

$.jStorage jQuery plugin:
[js]
// 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
[/js]

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

发表评论