10個好用的jQuery技巧

jQuery真的是一個很好學又好用的javascript library,不過在好學的同時,也應該學著怎麼把code寫的漂亮,這篇10 useful jQuery authoring tips有提供一些建議,我覺得超受用的,在寫的時候可以參考一下。

1.懶一點
// Don't
if ($('#item').get(0)) {
$('#item').someFunction();
}

// Or
if ($('#item').length) {
$('#item').someFunction();
}

// Just do
$('#item').someFunction();

不用去判斷元素存不存在,jQuery本身就會去判斷。

2.寫短一點
// You can but..
$(document).ready(function(){
// ...
});

// There is a shorter equivalent
$(function(){
// ...
});

同樣是呼叫jQuery,就用最短的方法就好了。

3.連鎖
// Don't
$('#frame').fadeIn();
$('#frame .title').show();
$('#frame a:visited').hide;

// Do
$('#frame').fadeIn()
.find('.title').show().end()
.find('a:visited').hide();

能連就連吧。

4.同樣的事情就一起做吧
// Ugly
$('div.close').click(closeCallback);
$('button.close').click(closeCallback);
$('input.close').click(closeCallback);

// Not ugly
$('div.close, button.close, input.close')
.click(closeCallback);

記得jQuery可以跟css一樣的選取元素。

5.像專家一樣用siblings吧
// Don't
$('#nav li').click(function(){
$('#nav li').removeClass('active');
$(this).addClass('active');
});

// Do
$('#nav li').click(function(){
$(this).addClass('active')
.siblings().removeClass('active');
});

siblings超好用的!!

6.使用each跟map
// Try to avoid
var output = [];
for (var i=0;i < arr.length; i++) { output.push(arr[i]); } // Do var output = $.map(arr, function() { ... }); // Or var output = []; $.each(arr, function(index, value) { output.push(value); });

jQuery的each跟map就有提供迴圈的功能了

7.使用namespace
Events can be namespaced

$('input').bind('blur.validation', function(e){
// ...
});

The data method also accept namespaces

$('input').data('validation.isValid', true);


8.很棒的triggerHandler
與其用var refreshFrame = function() {
$('#frame').load('http://reddit.com');
};

$('.button').click(refreshFrame);

refreshFrame();

不如考慮這樣用
$('.button').click(function() {
$('#frame').load('/page/frame.html');
}).triggerHandler('click');

// You can also use a shortcut
$('.button').click(function() {
$('#frame').load('/page/frame.html');
}).click();


9.客製化事件
$('.button').click(function() {
$('div#frame').load('/page/frame.html', function(){
$(this).triggerHandler('frameLoaded');
});
});

// PluginA.js
$('#frame').bind('frameLoaded', function(){
$(this).show('slide', {direction: 'top'});
});

// PluginB.js
$('div').bind('frameLoaded', function(){
// do something else
});


10.測試
module("A simple test");

test("The frame should appear #button is clicked", function() {
expect(1);
$('#button').click();
ok($('#frame').is(':visible'), "The frame is visible" );
});

可以引進jQuery的測試框架QUnit來寫測試

留言