一些jQuery的代碼和插件備忘錄

記錄一些常見的jQuery的用法例子

$('td:contains(Henry)') // Find every cell containing "Henry"
.parent() // Select its parent
.find('td:eq(1)') // Find the 2nd descendant cell
.addClass('highlight') // Add the "highlight" class
.end() // Return to the parent of the cell containing "Henry"
.find('td:eq(2)') // Find the 3rd descendant cell
.addClass('highlight'); // Add the "highlight" class

獲取索引對象
$('#my-element').get(0),或者使用$('#my-element:eq(0)')

與其他Js 類庫使用時,屏蔽自身的$
jQuery.noConflict(); // 關閉自身的$,使用時需要使用 jQuery("..")

在事件監聽函數中,使用$(this)訪問事件源對象,使用this訪問對應的HTML對象

!$(event.target).is('.button') //用於判斷事件觸發對象是否爲指定選擇器對象

$('#switcher').trigger('click'); //用於模擬用戶事件
$('#switcher').click(); //作用同上

在$(..)中的參數,也可以使用臨時拼接+的方式去獲取對象
多個css的設置
.css({property1: 'value1', 'property-2': 'value2'})

聲明jQuery對象變量的時候,建議使用$開頭--$name 作爲規範

鏈式的自定義動畫設置
.animate({left: paraWidth - switcherWidth},'slow')
.animate({height: '+=20px'}, 'slow')
.animate({borderWidth: '5px'}, 'slow');

內置動畫調用
$switcher
.fadeTo('fast',0.5)
.animate({'left': paraWidth - switcherWidth}, 'slow')
.fadeTo('slow',1.0)
.slideUp('slow')
.slideDown('slow');

也可以在其中加上對css的修改,達到更多樣的效果組合

在內置動畫的參數中,可以加入一個回調函數,在動畫結束後自動調用,也常用在回調函數中組合調用其他特效

注意在鏈式組成特效時,默認會同時發生, 可以使用.queue()方法在尾部設置成按照順序發生

$('<a href="#top">back to top</a>'); 用於創建包含HTML的jQuery對象,可以用於後面的插入等操作

.clone() 用於拷貝組件,當默認不拷貝事件,可以使用帶clone(true)來替換

1. To create new elements from HTML, user the $() factory function.
2. To insert new element(s) inside every matched element, use:
.append()
.appendTo()
.prepend()
.prependTo()
DOM Manipulation
[ 114 ]
3. To insert new element(s) adjacent to every matched element, use:
.after()
.insertAfter()
.before()
.insertBefore()
4. To insert new element(s) around every matched element, use:
.wrap()
.wrapAll()
.wrapInner()
5. To replace every matched element with new element(s) or text, use:
.html()
.text()
.replaceAll()
.replaceWith()
6. To remove element(s) inside every matched element, use:
.empty()
7. To remove every matched element and descendants from the document without actually deleting them, use:
.remove()

load方法的使用,常用語加載指定網頁的內容到指定的元素中
$('#dictionary').load('a.html');

直接獲取數據的Ajax方式
$.getJSON('b.json', function(data) {..}); //第二個爲回調函數,第一個爲json數據所在的url,未知是否需要保證頭信息裏面包含Json

$('#dictionary').empty(); // 用於清空指定元素的內容
$.getScript('c.js'); //用於異步加載js腳本

訪問異步加載的xml數據的方式
$(data).find('entry').each(function() {
var $entry = $(this); //使用循環獲取實體,如果實體爲集合,也可以再次使用each進行循環讀取
$entry.attr('term'); //訪問屬性
$entry.find('definition').text(); //訪問內容

$(data).find('entry:has(quote[author])').each(function() { } //更復雜的查詢,
'entry:has(quote[author 表示entry標籤下用於quote子標籤,而且其擁有author屬性

完整的異步提交表單數據的例子
$('#letter-f form').submit(function() {
$.get('f.php', $(this).serialize(), function(data) {
$('#dictionary').html(data);
});
return false; //阻止表單默認的提交,使用上面得Ajax方式提交數據
});

使用全局的Ajax方法,監聽Ajax動作的週期, //所謂全局的方法,就是可以作用在任何jQuery對象,當將會被其他任意的事件觸發的方法
$('<div id="loading">Loading...</div>')
.insertBefore('#dictionary')
.ajaxStart(function() {
$(this).show();
});

對於跨站點的數據獲取,可以使用JSONP方式
var url = 'http://www.examples.com/jsonp/g.php';
$.getJSON(url + '?callback=?', function(data) {..}

加載指定html中符合選擇器的部分內容
$('#dictionary').load('h.html .entry'); //使用選擇器進行部分加載

組合table,進行排序,異步加載結果集
<a href="index.php?sort=name">Name</a>
$('#my-data tbody').load($(this).attr('href'));
當使用Ajax提交的時候,將會把http header中的 X-Requested-With修改成 XMLHttpRequest,可以通過判斷,只要返回<tbody> 內容即可

使用銀灰色,能夠較好的區分odd 和even的tr

$('obj').each(function(index){$(this)}) //簡潔的使用each的方式

查找子元素的方式
var $search = $('#search').addClass('overlabel');
var $searchInput = $search.find('input');
var $searchLabel = $search.find('label');

一些js數字轉換的方式
var price = parseFloat($('td.price', this).text().replace(/^[^\d.]*/, ''));
price = isNaN(price) ? 0 : price;

var tax = Math.ceil(totalCost * taxRate * 100) / 100;
$('tr.tax td.cost').text('$' + tax.toFixed(2));
還有類似的parseInt等方法

批量設置樣式的方法
var $deleteButton = $('<img />').attr({
'width': '16',
'height': '16',
'src': '../images/cross.png',
'alt': 'remove from cart',
'title': 'remove from cart',
'class': 'clickable'
});

另外一種元素選擇器:
$("label","ul"). 用於得到ul下面所有的label元素

對元素大小的獲取
var startPos = $(this).offset();
startPos.width = $(this).width();
startPos.height = $(this).height();

標準的創建Json對象的方式
var b={};
b.atts=....; //添加屬性

用於判斷圖片加載完成的方式
if ($enlargedCover[0].complete) {
performAnimation();
}else {
$enlargedCover.bind('load', performAnimation); //這裏注意.load()爲jQuery的Ajax方法,所以需要bind
}

如果需要對顏色使用animate,需要添加jQuery color plugin,或者jQuery UI的 effects中也包含,提供多種擴展效果

插件所提供的其他效果
$('#sort-container').sortable({
opacity: .5,
cursor: 'move',
axis: 'y'
}) //對Li進行拖拉的排序功能

一些不錯的插件推薦
輸入:
Jeditable ---可編輯的table.
http://plugins.jquery.com/project/jeditable
Validation--基於css的驗證
http://plugins.jquery.com/project/validate
Autocomplete--自動完成
http://plugins.jquery.com/project/autocompletex
Masked input--提供對用戶輸入的輔助
http://plugins.jquery.com/project/maskedinput

Grid:表格
jqGrid --提供較完善的Table功能
http://plugins.jquery.com/project/jqGrids
Flexigrid--提供更簡單和靈活的grid表格,也更簡潔一些
http://plugins.jquery.com/project/flexigrid

Image圖片展示:
Jcrop -- 提供對圖片的截圖輔助
http://plugins.jquery.com/project/Jcrop
Magnify-- 局部放大圖片
http://www.jnathanson.com/index.cfm?page=jquery/magnify/magnify

更高級的圖片顯示,提供背景遮蓋
FancyBox --提供對圖片的高級瀏覽
http://fancy.klade.lv/
Thickbox -- 提供對內容的暫時,效果同上
http://jquery.com/demo/thickbox/
BlockUI -- 提供多樣可控的背景遮蓋
http://plugins.jquery.com/project/blockUI

圖表插件
Flot --簡單的圖片展示插件,但好像只有簡單的線,塊圖
http://plugins.jquery.com/project/flot

更多插件:
http://www.iteye.com/news/12391
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章