總之,Zepto希望在所有的現代瀏覽器中作為一種基礎環境來使用。Zepto不支持舊版本的Internet Explorer瀏覽器(<10)。
核心方法
$()
$(selector, [context]) ⇒ collection
$(<Zepto collection>) ⇒ same collection
$(<DOM nodes>) ⇒ collection
$(htmlString) ⇒ collection
$(htmlString, attributes) ⇒ collection v1.0+
Zepto(function($){ ... })
通過執行css選擇器,包裝dom節點,或者通過一個html字符串創建多個元素 來創建一個Zepto集合對象。
Zepto集合是一個類似數組的對象,它具有鏈式方法來操作它指向的DOM節點,除了$(
Zepto
)對象上的直接方法外(如$.extend
),文檔對象中的所有方法都是集合方法。
如果選擇器中存在content參數(css選擇器,dom,或者Zepto集合對象),那麼隻在所給的節點背景下進行css選擇器;這個功能和使用$(context).find(selector)
是一樣的。
當給定一個html字符串片段來創建一個dom節點時。也可以通過給定一組屬性映射來創建節點。最快的創建但元素,使用<div>
或 <div/>
形式。
當一個函數附加在 DOMContentLoaded
事件的處理流程中。如果頁麵已經加載完畢,這個方法將會立即被執行。
$('div') //=> 所有頁麵中得div元素
$('#foo') //=> ID 為 "foo" 的元素
// 創建元素:
$("<p>Hello</p>") //=> 新的p元素
// 創建帶有屬性的元素:
$("<p />", { text:"Hello", id:"greeting", css:{color:'darkblue'} })
//=> <p id=greeting style="color:darkblue">Hello</p>
// 當頁麵ready的時候,執行回調:
Zepto(function($){
alert('Ready to Zepto!')
})
不支持jQuery CSS 擴展,
然而,可選的“selector”模塊有限提供了支持幾個最常用的偽選擇器,而且可以被丟棄,與現有的代碼或插件的兼容執行。
如果$
變量尚未定義,Zepto隻設置了全局變量$
指向它本身。允許您同時使用的Zepto和有用的遺留代碼,例如,prototype.js。隻要首先加載Prototype,Zepto將不會覆蓋Prototype的 $
函數。Zepto將始終設置全局變量Zepto
指向它本身。
$.camelCase
v1.0+
$.camelCase(string) ⇒ string
將一組字符串變成“駱駝”命名法的新字符串,如果該字符已經是“駱駝”命名法,則不變化。
$.camelCase('hello-there') //=> "helloThere"
$.camelCase('helloThere') //=> "helloThere"
$.contains
v1.0+
$.contains(parent, node) ⇒ boolean
檢查父節點是否包含給定的dom節點,如果兩者是相同的節點,則返回 false
。
$.each
$.each(collection, function(index, item){ ... }) ⇒ collection
遍曆數組元素或以key-value值對方式遍曆對象。回調函數返回 false
時停止遍曆。
$.each(['a', 'b', 'c'], function(index, item){
console.log('item %d is: %s', index, item)
})
var hash = { name: 'zepto.js', size: 'micro' }
$.each(hash, function(key, value){
console.log('%s: %s', key, value)
})
$.extend
$.extend(target, [source, [source2, ...]]) ⇒ target
$.extend(true, target, [source, ...]) ⇒ target v1.0+
通過源對象擴展目標對象的屬性,源對象屬性將覆蓋目標對象屬性。
默認情況下為,複製為淺拷貝(淺複製)。如果第一個參數為true表示深度拷貝(深度複製)。
var target = { one: 'patridge' },
source = { two: 'turtle doves' }
$.extend(target, source)
//=> { one: 'patridge',
// two: 'turtle doves' }
$.fn
Zepto.fn
是一個對象,它擁有Zepto對象上所有可用的方法,如 addClass()
, attr()
,和其它方法。在這個對象添加一個方法,所有的Zepto對象上都能用到該方法。
這裏有一個實現 Zepto 的 empty()
方法的例子:
$.fn.empty = function(){
return this.each(function(){ this.innerHTML = '' })
}
$.grep
v1.0+
$.grep(items, function(item){ ... }) ⇒ array
獲取一個新數組,新數組隻包含回調函數中返回 ture 的數組項。
$.grep([1,2,3],function(item){
return item > 1
});//=>[2,3]
$.inArray
v1.0+
$.inArray(element, array, [fromIndex]) ⇒ number
返回數組中指定元素的索引值(愚人碼頭注:以0為基數),如果沒有找到該元素則返回-1
。
愚人碼頭注:[fromIndex]
參數可選,表示從哪個索引值開始向後查找。
$.inArray("abc",["bcd","abc","edf","aaa"]);//=>1
$.inArray("abc",["bcd","abc","edf","aaa"],1);//=>1
$.inArray("abc",["bcd","abc","edf","aaa"],2);//=>-1
$.isArray
$.isArray(object) ⇒ boolean
如果object是array,則返回ture。
$.isFunction
$.isFunction(object) ⇒ boolean
如果object是function,則返回ture。
$.isPlainObject
v1.0+
$.isPlainObject(object) ⇒ boolean
測試對象是否是“純粹”的對象,這個對象是通過 對象常量("{}") 或者 new Object
創建的,如果是,則返回true。
$.isPlainObject({}) // => true
$.isPlainObject(new Object) // => true
$.isPlainObject(new Date) // => false
$.isPlainObject(window) // => false
$.isWindow
v1.0+
$.isWindow(object) ⇒ boolean
如果object參數是否為一個window對象,那麼返回true。這在處理iframe時非常有用,因為每個iframe都有它們自己的window對象,使用常規方法obj === window
校驗這些objects的時候會失敗。
$.map
$.map(collection, function(item, index){ ... }) ⇒ collection
通過遍曆集合中的元素,返回通過迭代函數的全部結果,(愚人碼頭注:一個新數組)null
和 undefined
將被過濾掉。
$.map([1,2,3,4,5],function(item,index){
if(item>1){return item*item;}
});
// =>[4, 9, 16, 25]
$.map({"yao":1,"tai":2,"yang":3},function(item,index){
if(item>1){return item*item;}
});
// =>[4, 9]
$.parseJSON
v1.0+
$.parseJSON(string) ⇒ object
原生JSON.parse
方法的別名。(愚人碼頭注:接受一個標準格式的 JSON 字符串,並返回解析後的 JavaScript 對象。)
$.trim
v1.0+
$.trim(string) ⇒ string
刪除字符串首尾的空白符。類似String.prototype.trim()。
$.type
v1.0+
$.type(object) ⇒ string
獲取JavaScript 對象的類型。可能的類型有: null
undefined
boolean
number
string
function
array
date
regexp
object
error
。
對於其它對象,它隻是簡單報告為“object”,如果你想知道一個對象是否是一個javascript普通對象,使用 isPlainObject。
add
add(selector, [context]) ⇒ self
添加元素到當前匹配的元素集合中。如果給定content參數,將隻在content元素中進行查找,否則在整個document中查找。
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>
<p>a paragraph</p>
<script type="text/javascript">
$('li').add('p').css('background-color', 'red');
</script>
addClass
addClass(name) ⇒ self
addClass(function(index, oldClassName){ ... }) ⇒ self
為每個匹配的元素添加指定的class類名。多個class類名使用空格分隔。
after
after(content) ⇒ self
在每個匹配的元素後插入內容(愚人碼頭注:外部插入)。內容可以為html字符串,dom節點,或者節點組成的數組。
$('form label').after('<p>A note below the label</p>')
append
append(content) ⇒ self
在每個匹配的元素末尾插入內容(愚人碼頭注:內部插入)。內容可以為html字符串,dom節點,或者節點組成的數組。
$('ul').append('<li>new list item</li>')
appendTo
appendTo(target) ⇒ self
將匹配的元素插入到目標元素的末尾(愚人碼頭注:內部插入)。這個有點像 append,但是插入的目標與其相反。
$('<li>new list item</li>').appendTo('ul')
attr
attr(name) ⇒ string
attr(name, value) ⇒ self
attr(name, function(index, oldValue){ ... }) ⇒ self
attr({ name: value, name2: value2, ... }) ⇒ self
讀取或設置dom的屬性。如果沒有給定value參數,則讀取對象集合中第一個元素的屬性值。當給定了value參數。則設置對象集合中所有元素的該屬性的值。當value參數為null
,那麼這個屬性將被移除(類似removeAttr),多個屬性可以通過對象鍵值對的方式進行設置。
要讀取DOM的屬性如 checked
和selected
, 使用 prop。
var form = $('form')
form.attr('action') //=> 讀取值
form.attr('action', '/create') //=> 設置值
form.attr('action', null) //=> 移除屬性
// 多個屬性:
form.attr({
action: '/create',
method: 'post'
})
before
before(content) ⇒ self
在匹配每個元素的前麵插入內容(愚人碼頭注:外部插入)。內容可以為html字符串,dom節點,或者節點組成的數組。
$('table').before('<p>See the following table:</p>')
children
children([selector]) ⇒ collection
獲得每個匹配元素集合元素的直接子元素,如果給定selector,那麼返回的結果中隻包含符合css選擇器的元素。
$('ol').children('*:nth-child(2n)')
//=> every other list item from every ordered list
clone
v1.0+
clone() ⇒ collection
通過深度克隆來複製集合中的所有元素。
此方法不會將數據和事件處理程序複製到新的元素。這點和jquery中利用一個參數來確定是否複製數據和事件處理不相同。
closest
closest(selector, [context]) ⇒ collection
closest(collection) ⇒ collection v1.0+
closest(element) ⇒ collection v1.0+
從元素本身開始,逐級向上級元素匹配,並返回最先匹配selector的元素。如果給定context節點參數,那麼隻匹配該節點的後代元素。這個方法與
parents(selector)
有點相像,但它隻返回最先匹配的祖先元素。
如果參數是一個Zepto對象集合或者一個元素,結果必須匹配給定的元素而不是選擇器。
var input = $('input[type=text]')
input.closest('form')
concat
concat(nodes, [node2, ...]) ⇒ self
添加元素到一個Zepto對象集合形成一個新數組。如果參數是一個數組,那麼這個數組中的元素將會合並到Zepto對象集合中。
這是一個Zepto提供的方法,不是jquey的API 。
contents
v1.0+
contents() ⇒ collection
獲得每個匹配元素集合元素的子元素,包括文字和注釋節點。(愚人碼頭注:.contents()和.children()方法類似,隻不過前者包括文本節點以及jQuery對象中產生的HTML元素。)
css
css(property) ⇒ value
css([property1, property2, ...]) ⇒ object v1.1+
css(property, value) ⇒ self
css({ property: value, property2: value2, ... }) ⇒ self
讀取或設置DOM元素的css屬性。當value參數不存在的時候,返回對象集合中第一個元素的css屬性。當value參數存在時,設置對象集合中每一個元素的對應css屬性。
多個屬性可以通過傳遞一個屬性名組成的數組一次性獲取。多個屬性可以利用對象鍵值對的方式進行設置。
當value為空(空字符串,null
或 undefined
),那個css屬性將會被移出。當value參數為一個無單位的數字,如果該css屬性需要單位,“px”將會自動添加到該屬性上。
var elem = $('h1')
elem.css('background-color') // read property
elem.css('background-color', '#369') // set property
elem.css('background-color', '') // remove property
// set multiple properties:
elem.css({ backgroundColor: '#8EE', fontSize: 28 })
// read multiple properties:
elem.css(['backgroundColor', 'fontSize'])['fontSize']
data
data(name) ⇒ value
data(name, value) ⇒ self
讀取或寫入dom的 data-*
屬性。行為有點像 attr ,但是屬性名稱前麵加上
data-
。
當讀取屬性值時,會有下列轉換:v1.0+
each
each(function(index, item){ ... }) ⇒ self
遍曆一個對象集合每個元素。在迭代函數中,this
關鍵字指向當前項(作為函數的第二個參數傳遞)。如果迭代函數返回 false
,遍曆結束。
$('form input').each(function(index){
console.log('input %d is: %o', index, this)
})
empty
empty() ⇒ self
清空對象集合中每個元素的DOM內容。
eq
eq(index) ⇒ collection
從當前對象集合中獲取給定索引值(愚人碼頭注:以0為基數)的元素。
$('li').eq(0) //=> only the first list item
$('li').eq(-1) //=> only the last list item
filter
filter(selector) ⇒ collection
filter(function(index){ ... }) ⇒ collection v1.0+
過濾對象集合,返回對象集合中滿足css選擇器的項。如果參數為一個函數,函數返回有實際值得時候,元素才會被返回。在函數中, this
關鍵字指向當前的元素。
與此相反的功能,查看not.
find
find(selector) ⇒ collection
find(collection) ⇒ collection v1.0+
find(element) ⇒ collection v1.0+
在當對象前集合內查找符合CSS選擇器的每個元素的後代元素。
如果給定Zepto對象集合或者元素,過濾它們,隻有當它們在當前Zepto集合對象中時,才回被返回。
var form = $('#myform')
form.find('input, select')
first
first() ⇒ collection
獲取當前對象集合中的第一個元素。
forEach
forEach(function(item, index, array){ ... }, [context])
遍曆對象集合中每個元素,有點類似 each,但是遍曆函數的參數不一樣,當函數返回 false
的時候,遍曆不會停止。
這是一個Zepto提供的方法,不是jquery的API。
get
get() ⇒ array
get(index) ⇒ DOM node
從當前對象集合中獲取所有元素或單個元素。當index參數不存在的時,以普通數組的方式返回所有的元素。當指定index時,隻返回該置的元素。這點與eq不同,該方法返回的是DOM節點,不是Zepto對象集合。
var elements = $('h2')
elements.get() //=> get all headings as an array
elements.get(0) //=> get first heading node
has
v1.0+
has(selector) ⇒ collection
has(node) ⇒ collection
判斷當前對象集合的子元素是否有符合選擇器的元素,或者是否包含指定的DOM節點,如果有,則返回新的對象集合,該對象過濾掉不含有選擇器匹配元素或者不含有指定DOM節點的對象。
$('ol > li').has('a[href]')
//=> get only LI elements that contain links
hasClass
hasClass(name) ⇒ boolean
檢查對象集合中是否有元素含有指定的class。
<ul>
<li>list item 1</li>
<li class="yaotaiyang">list item 2</li>
<li>list item 3</li>
</ul>
<p>a paragraph</p>
<script type="text/javascript">
$("li").hasClass("yaotaiyang");
//=> true
</script>
height
height() ⇒ number
height(value) ⇒ self
height(function(index, oldHeight){ ... }) ⇒ self
獲取對象集合中第一個元素的高度;或者設置對象集合中所有元素的高度。
$('#foo').height() // => 123
$(window).height() // => 838 (viewport height)
$(document).height() // => 22302
hide
hide() ⇒ self
Hide elements in this collection by setting their display
CSS property to
none
.
通過設置css的屬性display
為 none
來將對象集合中的元素隱藏。
html
html() ⇒ string
html(content) ⇒ self
html(function(index, oldHtml){ ... }) ⇒ self
獲取或設置對象集合中元素的HTML內容。當沒有給定content參數時,返回對象集合中第一個元素的innerHtml。當給定content參數時,用其替換對象集合中每個元素的內容。content可以是append中描述的所有類型。
// autolink everything that looks like a Twitter username
$('.comment p').html(function(idx, oldHtml){
return oldHtml.replace(/(^|\W)@(\w{1,15})/g,
'$1@<a href="http://twitter.com/$2">$2</a>')
})
index
index([element]) ⇒ number
獲取一個元素的索引值(愚人碼頭注:從0開始計數)。當elemen參數沒有給出時,返回當前元素在兄弟節點中的位置。當element參數給出時,返回它在當前對象集合中的位置。如果沒有找到該元素,則返回-1
。
$('li:nth-child(2)').index() //=> 1
indexOf
indexOf(element, [fromIndex]) ⇒ number
Get the position of an element in the current collection. If fromIndex number is
given, search only from that position onwards. Returns the 0-based position when
found and -1
if not found. Use of index is recommended over this
method.
在當前對象集合中獲取一個元素的索引值(愚人碼頭注:從0開始計數)。如果給定formindex參數,從該位置開始往後查找,返回基於0的索引值,如果沒找到,則返回-1
。index 方法是基於這個方法實現的。
這是一個Zepto的方法,不是jquer的api。
insertAfter
insertAfter(target) ⇒ self
將集合中的元素插入到指定的目標元素後麵(愚人碼頭注:外部插入)。這個有點像 after,但是使用方式相反。
$('<p>Emphasis mine.</p>').insertAfter('blockquote')
insertBefore
insertBefore(target) ⇒ self
將集合中的元素插入到指定的目標元素前麵(愚人碼頭注:外部插入)。這個有點像 before,但是使用方式相反。
$('<p>See the following table:</p>').insertBefore('table')
is
is(selector) ⇒ boolean
判斷當前元素集合中的第一個元素是否符css選擇器。對於基礎支持jquery的非標準選擇器類似: :visible
包含在可選的“selector”模塊中。
jQuery
CSS extensions 不被支持。 選擇“selector”模塊僅僅能支持有限幾個最常用的方式。
last
last() ⇒ collection
獲取對象集合中最後一個元素。
map
map(function(index, item){ ... }) ⇒ collection
遍曆對象集合中的所有元素。通過遍曆函數返回值形成一個新的集合對象。在遍曆函數中this
關鍵之指向當前循環的項(遍曆函數中的第二個參數)。
遍曆中返回 null
和undefined
,遍曆將結束。
// get text contents of all elements in collection
elements.map(function(){ return $(this).text() }).get().join(', ')
next
next() ⇒ collection
next(selector) ⇒ collection v1.0+
Get the next sibling–optionally filtered by selector–of each element in the
collection.
獲取對象集合中每一個元素的下一個兄弟節點(可以選擇性的帶上過濾選擇器)。
$('dl dt').next() //=> the DD elements
not
not(selector) ⇒ collection
not(collection) ⇒ collection
not(function(index){ ... }) ⇒ collection
過濾當前對象集合,獲取一個新的對象集合,它裏麵的元素不能匹配css選擇器。如果另一個參數為Zepto對象集合,那麼返回的新Zepto對象中的元素都不包含在該參數對象中。如果參數是一個函數。僅僅包含函數執行為false值得時候的元素,函數的
this
關鍵字指向當前循環元素。
與它相反的功能,查看 filter.
offset
offset() ⇒ object
offset(coordinates) ⇒ self v1.0+
offset(function(index, oldOffset){ ... }) ⇒ self v1.0+
獲得當前元素相對於document的位置。返回一個對象含有:
top
, left
, width
和height
當給定一個含有left
和top
屬性對象時,使用這些值來對集合中每一個元素進行相對於document的定位。
offsetParent
v1.0+
offsetParent() ⇒ collection
找到第一個定位過的祖先元素,意味著它的css中的position
屬性值為“relative”, “absolute” or “fixed”
parent
parent([selector]) ⇒ collection
獲取對象集合中每個元素的直接父元素。如果css選擇器參數給出。過濾出符合條件的元素。
parents
parents([selector]) ⇒ collection
獲取對象集合每個元素所有的祖先元素。如果css選擇器參數給出,過濾出符合條件的元素。
如果想獲取直接父級元素,使用 parent。如果隻想獲取到第一個符合css選擇器的元素,使用closest。
$('h1').parents() //=> [<div#container>, <body>, <html>]
pluck
pluck(property) ⇒ array
獲取對象集合中每一個元素的屬性值。返回值為 null
或undefined
值得過濾掉。
$('body > *').pluck('nodeName') // => ["DIV", "SCRIPT"]
// implementation of Zepto's `next` method
$.fn.next = function(){
return $(this.pluck('nextElementSibling'))
}
這是一個Zepto的方法,不是jquery的api
position
v1.0+
position() ⇒ object
獲取對象集合中第一個元素的位置。相對於
offsetParent。當絕對定位的一個元素靠近另一個元素的時候,這個方法是有用的。
Returns an object with properties: top
, left
.
var pos = element.position()
// position a tooltip relative to the element
$('#tooltip').css({
position: 'absolute',
top: pos.top - 30,
left: pos.left
})
prepend
prepend(content) ⇒ self
將參數內容插入到每個匹配元素的前麵(愚人碼頭注:元素內部插入)。插入d的元素可以試html字符串片段,一個dom節點,或者一個節點的數組。
$('ul').prepend('<li>first list item</li>')
prependTo
prependTo(target) ⇒ self
將所有元素插入到目標前麵(愚人碼頭注:元素內部插入)。這有點像prepend,但是是相反的方式。
$('<li>first list item</li>').prependTo('ul')
prev
prev() ⇒ collection
prev(selector) ⇒ collection v1.0+
獲取對象集合中每一個元素的前一個兄弟節點,通過選擇器來進行過濾。
prop
v1.0+
prop(name) ⇒ value
prop(name, value) ⇒ self
prop(name, function(index, oldValue){ ... }) ⇒ self
讀取或設置dom元素的屬性值。它在讀取屬性值的情況下優先於 attr,因為這些屬性值會因為用戶的交互發生改變,如checked
和
selected
。
簡寫或小寫名稱,比如for
, class
, readonly
及類似的屬性,將被映射到實際的屬性上,比如htmlFor
, className
, readOnly
, 等等。
push
push(element, [element2, ...]) ⇒ self
Add elements to the end of the current collection.
添加元素到當前對象集合的最後。
這是一個zepto的方法,不是jquery的api
ready
ready(function($){ ... }) ⇒ self
添加一個事件偵聽器,當頁麵DOM加載完畢 “DOMContentLoaded” 事件觸發時觸發。建議使用 $()來代替這種用法。
reduce
reduce(function(memo, item, index, array){ ... }, [initial]) ⇒ value
與 Array.reduce有相同的用法,遍曆當前對象集合。memo是函數上次的返回值。迭代進行遍曆。
這是一個zepto的方法,不是jquery的api
remove
remove() ⇒ self
從其父節點中刪除當前集合中的元素,有效的從dom中移除。
removeAttr
removeAttr(name) ⇒ self
移除當前對象集合中所有元素的指定屬性。
removeClass
removeClass([name]) ⇒ self
removeClass(function(index, oldClassName){ ... }) ⇒ self
移除當前對象集合中所有元素的指定class。如果沒有指定name參數,將移出所有的class。多個class參數名稱可以利用空格分隔。下例移除了兩個class。
<input class="taiyang yueliang" id="check1" type="checkbox" checked="checked">
<input class="yaotaiyang" id="check2" type="checkbox">
<script type="text/javascript">
$("#check1").removeClass("taiyang yueliang")
//=>[<input class id="check1" type="checkbox" checked="checked">]
</script>
replaceWith
replaceWith(content) ⇒ self
用給定的內容替換所有匹配的元素。(包含元素本身)。content參數可以為
before中描述的類型。
scrollLeft
v1.1+
scrollLeft() ⇒ number
scrollLeft(value) ⇒ self
獲取或設置頁麵上的滾動元素或者整個窗口向右滾動的像素值。
scrollTop
v1.0+
scrollTop() ⇒ number
scrollTop(value) ⇒ self v1.1+
獲取或設置頁麵上的滾動元素或者整個窗口向下滾動的像素值。
show
show() ⇒ self
恢複對象集合中每個元素默認的“display”值。如果你用 hide將元素隱藏,用該屬性可以將其顯示。相當於去掉了display:none
。
siblings
siblings([selector]) ⇒ collection
獲取對象集合中所有元素的兄弟節點。如果給定CSS選擇器參數,過濾出符合選擇器的元素。
size
size() ⇒ number
獲取對象集合中元素的數量。
slice
slice(start, [end]) ⇒ array
提取這個數組array
的子集,從start
開始,如果給定end
,提取從從start
開始到end
結束的元素,但是不包含end
位置的元素。
text
text() ⇒ string
text(content) ⇒ self
text(function(index, oldText){ ... }) ⇒ self v1.1.4+
獲取或者設置所有對象集合中元素的文本內容。當沒有給定content參數時,返回當前對象集合中第一個元素的文本內容(包含子節點中的文本內容)。當給定content參數時,使用它替換對象集合中所有元素的文本內容。它有待點似
html,與它不同的是它不能用來獲取或設置 HTML。
toggle
toggle([setting]) ⇒ self
顯示或隱藏匹配元素。如果 setting
為true,相當於show 法。如果setting
為false。相當於
hide方法。
var input = $('input[type=text]')
$('#too_long').toggle(input.val().length > 140)
toggleClass
toggleClass(names, [setting]) ⇒ self
toggleClass(function(index, oldClassNames){ ... }, [setting]) ⇒ self
在匹配的元素集合中的每個元素上添加或刪除一個或多個樣式類。如果class的名稱存在則刪除它,如果不存在,就添加它。如果 setting
的值為真,這個功能類似於
addClass,如果為假,這個功能類似與 removeClass。
unwrap
unwrap() ⇒ self
移除集合中每個元素的直接父節點,並把他們的子元素保留在原來的位置。
基本上,這種方法刪除上一的祖先元素,同時保持DOM中的當前元素。
$(document.body).append('<div id=wrapper><p>Content</p></div>')
$('#wrapper p').unwrap().parents() //=> [<body>, <html>]
val
val() ⇒ string
val(value) ⇒ self
val(function(index, oldValue){ ... }) ⇒ self
獲取或設置匹配元素的值。當沒有給定value參數,返回第一個元素的值。如果是<select multiple>
標簽,則返回一個數組。當給定value參數,那麼將設置所有元素的值。
width
width() ⇒ number
width(value) ⇒ self
width(function(index, oldWidth){ ... }) ⇒ self
獲取對象集合中第一個元素的寬;或者設置對象集合中所有元素的寬。
$('#foo').width() // => 123
$(window).width() // => 768 (viewport width)
$(document).width() // => 768
wrap
wrap(structure) ⇒ self
wrap(function(index){ ... }) ⇒ self v1.0+
在每個匹配的元素外層包上一個html元素。structure參數可以是一個單獨的元素或者一些嵌套的元素。也可以是一個html字符串片段或者dom節點。還可以是一個生成用來包元素的回調函數,這個函數返回前兩種類型的包裹片段。
需要提醒的是:該方法對於dom中的節點有著很好的支持。如果將wrap()
用在一個新的元素上,然後再將結果插入到document中,此時該方法無效。
// wrap each button in a separate span:
$('.buttons a').wrap('<span>')
// wrap each code block in a div and pre:
$('code').wrap('<div class=highlight><pre /></div>')
// wrap all form inputs in a span with classname
// corresponding to input type:
$('input').wrap(function(index){
return '<span class=' + this.type + 'field />'
})
//=> <span class=textfield><input type=text /></span>,
// <span class=searchfield><input type=search /></span>
// WARNING: will not work as expected!
$('<em>broken</em>').wrap('<li>').appendTo(document.body)
// do this instead:
$('<em>better</em>').appendTo(document.body).wrap('<li>')
wrapAll
wrapAll(structure) ⇒ self
在所有匹配元素外麵包一個單獨的結構。結構可以是單個元素或
幾個嵌套的元素,並且可以通過在作為HTML字符串或DOM節點。
// wrap all buttons in a single div:
$('a.button').wrapAll('<div id=buttons />')
wrapInner
wrapInner(structure) ⇒ self
wrapInner(function(index){ ... }) ⇒ self v1.0+
將每個元素中的內容包裹在一個單獨的結構中。結構可以是單個元件或多個嵌套元件,並且可以通過在作為HTML字符串或DOM節點,或者是一個生成用來包元素的回調函數,這個函數返回前兩種類型的包裹片段。
// wrap the contents of each navigation link in a span:
$('nav a').wrapInner('<span>')
// wrap the contents of each list item in a paragraph and emphasis:
$('ol li').wrapInner('<p><em /></p>')
Detect methods
Detect module
該檢測方法可以在不同的環境中微調你的站點或者應用程序,並幫助你識別手機和平板;以及不同的瀏覽器和操作係統。
// The following boolean flags are set to true if they apply,
// if not they're either set to `false` or `undefined`.
// We recommend accessing them with `!!` prefixed to coerce to a boolean.
// general device type
$.os.phone
$.os.tablet
// specific OS
$.os.ios
$.os.android
$.os.webos
$.os.blackberry
$.os.bb10
$.os.rimtabletos
// specific device type
$.os.iphone
$.os.ipad
$.os.ipod // [v1.1]
$.os.touchpad
$.os.kindle
// specific browser
$.browser.chrome
$.browser.firefox
$.browser.safari // [v1.1]
$.browser.webview // (iOS) [v1.1]
$.browser.silk
$.browser.playbook
$.browser.ie // [v1.1]
// 此外,版本信息是可用的。
// 下麵是運行iOS 6.1的iPhone所返回的。
!!$.os.phone // => true
!!$.os.iphone // => true
!!$.os.ios // => true
$.os.version // => "6.1"
$.browser.version // => "536.26"
事件處理
$.Event
$.Event(type, [properties]) ⇒ event
創建並初始化一個指定的DOM事件。如果給定properties對象,使用它來擴展出新的事件對象。默認情況下,事件被設置為冒泡方式;這個可以通過設置bubbles
為false
來關閉。
一個事件初始化的函數可以使用
trigger來觸發。
$.Event('mylib:change', { bubbles: false })
$.proxy
v1.0+
$.proxy(fn, context) ⇒ function
$.proxy(fn, context, [additionalArguments...]) ⇒ function v1.1.4+
$.proxy(context, property) ⇒ function
$.proxy(context, property, [additionalArguments...]) ⇒ function v1.1.4+
接受一個函數,然後返回一個新函數,並且這個新函數始終保持了特定的上下文(context)語境,新函數中this
指向context參數。另外一種形式,原始的function是從上下文(context)對象的特定屬性讀取。
如果傳遞超過2個的額外參數,它們被用於 傳遞給fn參數的函數 引用。
var obj = {name: 'Zepto'},
handler = function(){ console.log("hello from + ", this.name) }
// ensures that the handler will be executed in the context of `obj`:
$(document).on('click', $.proxy(handler, obj))
bind
🐶🔫
不推薦, 使用 on 代替。
bind(type, function(e){ ... }) ⇒ self
bind(type, [data], function(e){ ... }) ⇒ self v1.1+
bind({ type: handler, type2: handler2, ... }) ⇒ self
bind({ type: handler, type2: handler2, ... }, [data]) ⇒ self v1.1+
為一個元素綁定一個處理事件。
delegate
🐶🔫
不推薦, 使用 on 代替。
delegate(selector, type, function(e){ ... }) ⇒ self
delegate(selector, { type: handler, type2: handler2, ... }) ⇒ self
基於一組特定的根元素為所有選擇器匹配的元素附加一個處理事件,匹配的元素可能現在或將來才創建。
die
🐶🔫
不推薦, 使用 on 代替。
die(type, function(e){ ... }) ⇒ self
die({ type: handler, type2: handler2, ... }) ⇒ self
刪除通過 live 添加的事件。
event.isDefaultPrevented
v1.1+
event.isDefaultPrevented() ⇒ boolean
如果preventDefault()
被該事件的實例調用,那麼返回true。
這可作為跨平台的替代原生的 defaultPrevented
屬性,如果 defaultPrevented
缺失或在某些瀏覽器下不可靠的時候。
// trigger a custom event and check whether it was cancelled
var event = $.Event('custom')
element.trigger(event)
event.isDefaultPrevented()
event.isImmediatePropagationStopped
v1.1+
event.isImmediatePropagationStopped() ⇒ boolean
如果stopImmediatePropagation()
被該事件的實例調用,那麼返回true。Zepto在不支持該原生方法的瀏覽器中實現它,
(例如老版本的Android)。
event.isPropagationStopped
v1.1+
event.isPropagationStopped() ⇒ boolean
如果stopPropagation()
被該事件的實例調用,那麼返回true。
live
🐶🔫
不推薦, 使用 on 代替。
live(type, function(e){ ... }) ⇒ self
live({ type: handler, type2: handler2, ... }) ⇒ self
類似delegate,添加一個個事件處理器到符合目前選擇器的所有元素匹配,匹配的元素可能現在或將來才創建。
off
off(type, [selector], function(e){ ... }) ⇒ self
off({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
off(type, [selector]) ⇒ self
off() ⇒ self
移除通過 on 添加的事件.移除一個特定的事件處理程序,
必須通過用on()
添加的那個相同的函數。否則,隻通過事件類型調用此方法將移除該類型的所有處理程序。如果沒有參數,將移出當前元素上全部的注冊事件。
on
on(type, [selector], function(e){ ... }) ⇒ self
on(type, [selector], [data], function(e){ ... }) ⇒ self v1.1+
on({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
on({ type: handler, type2: handler2, ... }, [selector], [data]) ⇒ self v1.1+
添加事件處理程序到對象集合中得元素上。多個事件可以通過空格的字符串方式添加,或者以事件類型為鍵、以函數為值的對象 方式。如果給定css選擇器,當事件在匹配該選擇器的元素上發起時,事件才會被觸發(愚人碼頭注:即事件委派,或者說事件代理)。
如果給定data
參數,這個值將在事件處理程序執行期間被作為有用的
event.data
屬性
事件處理程序在添加該處理程序的元素、或在給定選擇器情況下匹配該選擇器的元素的上下文中執行(愚人碼頭注:this指向觸發事件的元素)。
當一個事件處理程序返回false
,preventDefault()
和 stopPropagation()
被當前事件調用的情況下,
將防止默認瀏覽器操作,如鏈接。
如果false
在回調函數的位置上作為參數傳遞給這個方法,
它相當於傳遞一個函數,這個函數直接返回false
。(愚人碼頭注:即將 false
當作 function(e){ ... }
的參數,作為 function(){ return false; }
的簡寫形式,例如: $("a.disabled").on("click", false);
這相當於$("a.disabled").on("click", function(){ return false; } );
)
var elem = $('#content')
// observe all clicks inside #content:
elem.on('click', function(e){ ... })
// observe clicks inside navigation links in #content
elem.on('click', 'nav a', function(e){ ... })
// all clicks inside links in the document
$(document).on('click', 'a', function(e){ ... })
// disable following any navigation link on the page
$(document).on('click', 'nav a', false)
one
one(type, [selector], function(e){ ... }) ⇒ self
one(type, [selector], [data], function(e){ ... }) ⇒ self v1.1+
one({ type: handler, type2: handler2, ... }, [selector]) ⇒ self
one({ type: handler, type2: handler2, ... }, [selector], [data]) ⇒ self v1.1+
添加一個處理事件到元素,當第一次執行事件以後,該事件將自動解除綁定,保證處理函數在每個元素上最多執行一次。selector
和 data
等參數說明請查看.on()
。
trigger
trigger(event, [args]) ⇒ self
在對象集合的元素上觸發指定的事件。事件可以是一個字符串類型,也可以是一個 通過$.Event 定義的事件對象。如果給定args參數,它會作為參數傳遞給事件函數。
// add a handler for a custom event
$(document).on('mylib:change', function(e, from, to){
console.log('change on %o with data %s, %s', e.target, from, to)
})
// trigger the custom event
$(document.body).trigger('mylib:change', ['one', 'two'])
Zepto僅僅支持在dom元素上觸發事件。
triggerHandler
triggerHandler(event, [args]) ⇒ self
像 trigger,它隻在當前元素上觸發事件,但不冒泡。
$("input").triggerHandler('focus');
// 此時input上的focus事件觸發,但是input不會獲取焦點
$("input").trigger('focus');
// 此時input上的focus事件觸發,input獲取焦點
unbind
🐶🔫
Deprecated, use off instead.
unbind(type, function(e){ ... }) ⇒ self
unbind({ type: handler, type2: handler2, ... }) ⇒ self
移除通過 bind 注冊的事件。
undelegate
🐶🔫
Deprecated, use off instead.
undelegate(selector, type, function(e){ ... }) ⇒ self
undelegate(selector, { type: handler, type2: handler2, ... }) ⇒ self
移除通過delegate 注冊的事件。
Ajax 請求
$.ajax
$.ajax(options) ⇒ XMLHttpRequest
執行Ajax請求。它可以是本地資源,或者通過支持HTTP access control的瀏覽器
或者通過 JSONP來實現跨域。
選項:
type
(默認: “GET”):請求方法 (“GET”, “POST”, or other)
url
(默認: 當前地址):發送請求的地址
data
(默認:none):發送到服務器的數據;如果是GET請求,它會自動被作為參數拚接到url上。非String對象將通過
$.param 得到序列化字符串。
processData
(默認: true): 對於非Get請求。是否自動將 data
轉換為字符串。
contentType
(默認: “application/x-www-form-urlencoded”): 發送信息至服務器時內容編碼類型。 (這也可以通過設置
headers
)。通過設置 false
跳過設置默認值。
mimeType
(默認: none): 覆蓋響應的MIME類型。
v1.1+
dataType
(默認: none):預期服務器返回的數據類型(“json”, “jsonp”, “xml”, “html”, or “text”)
jsonp
(默認:“callback”): JSONP回調查詢參數的名稱
jsonpCallback
(默認: “jsonp{N}”): 全局JSONP回調函數的 字符串(或返回的一個函數)名。設置該項能啟用瀏覽器的緩存。
v1.1+
timeout
(默認: 0
): 以毫秒為單位的請求超時時間, 0
表示不超時。
headers
: Ajax請求中額外的HTTP信息頭對象
async
(默認:true): 默認設置下,所有請求均為異步。如果需發送同步請求,請將此設置為 false
。
global
(默認:true): 請求將觸發全局Ajax事件處理程序,設置為 false 將不會觸發全局 Ajax 事件。
context
(默認:window): 這個對象用於設置Ajax相關回調函數的上下文(this指向)。
traditional
(默認: false): 激活傳統的方式通過$.param來得到序列化的 data
。
cache
(默認: true): 瀏覽器是否應該被允許緩存GET響應。從v1.1.4開始,當dataType選項為 "script"
或 jsonp
時,默認為false
。
xhrFields
(默認: none): 一個對象包含的屬性被逐字複製到XMLHttpRequest的實例。
v1.1+
username
& password
(默認: none): HTTP基本身份驗證憑據。
v1.1+
如果URL中含有 =?
或者dataType
是“jsonp”,這講求將會通過注入一個
<script>
標簽來代替使用 XMLHttpRequest (查看 JSONP)。此時
contentType
, dataType
, headers
有限製,async
不被支持。
Ajax 回調函數
你可以指定以下的回調函數,他們將按給定的順序執行:
-
beforeSend(xhr, settings)
:請求發出前調用,它接收xhr對象和settings作為參數對象。如果它返回 false
,請求將被取消。
-
success(data, status, xhr)
:請求成功之後調用。傳入返回後的數據,以及包含成功代碼的字符串。
-
error(xhr, errorType, error)
:請求出錯時調用。 (超時,解析錯誤,或者狀態碼不在HTTP 2xx)。
-
complete(xhr, status)
:請求完成時調用,無論請求失敗或成功。
Promise 回調接口 v1.1+
如果可選的“callbacks” 和 “deferred” 模塊被加載,從$.ajax()
返回的XHR對象實現了promise接口鏈式的回調:
xhr.done(function(data, status, xhr){ ... })
xhr.fail(function(xhr, errorType, error){ ... })
xhr.always(function(){ ... })
xhr.then(function(){ ... })
這些方法取代了 success
, error
, 和 complete
回調選項.
Ajax 事件
當global: true
時。在Ajax請求生命周期內,以下這些事件將被觸發。
-
ajaxStart
(global):如果沒有其他Ajax請求當前活躍將會被觸發。
-
ajaxBeforeSend
(data: xhr, options):再發送請求前,可以被取消。
-
ajaxSend
(data: xhr, options):像 ajaxBeforeSend
,但不能取消。
-
ajaxSuccess
(data: xhr, options, data):當返回成功時。
-
ajaxError
(data: xhr, options, error):當有錯誤時。
-
ajaxComplete
(data: xhr, options):請求已經完成後,無論請求是成功或者失敗。
-
ajaxStop
(global):如果這是最後一個活躍著的Ajax請求,將會被觸發。
默認情況下,Ajax事件在document對象上觸發。然而,如果請求的
context
是一個DOM節點,該事件會在此節點上觸發然後再DOM中冒泡。唯一的例外是 ajaxStart
& ajaxStop
這兩個全局事件。
$(document).on('ajaxBeforeSend', function(e, xhr, options){
// This gets fired for every Ajax request performed on the page.
// The xhr object and $.ajax() options are available for editing.
// Return false to cancel this request.
})
$.ajax({
type: 'GET',
url: '/projects',
// data to be added to query string:
data: { name: 'Zepto.js' },
// type of data we are expecting in return:
dataType: 'json',
timeout: 300,
context: $('body'),
success: function(data){
// Supposing this JSON payload was received:
// {"project": {"id": 42, "html": "<div>..." }}
// append the HTML to context object.
this.append(data.project.html)
},
error: function(xhr, type){
alert('Ajax error!')
}
})
// post a JSON payload:
$.ajax({
type: 'POST',
url: '/projects',
// post payload:
data: JSON.stringify({ name: 'Zepto.js' }),
contentType: 'application/json'
})
$.ajaxJSONP
🐶🔫
不推薦, 使用 $.ajax 代替。
$.ajaxJSONP(options) ⇒ mock XMLHttpRequest
執行JSONP跨域獲取數據。
此方法相對 $.ajax 沒有優勢,建議不要使用。
$.ajaxSettings
一個包含Ajax請求的默認設置的對象。大部分的設置在 $.ajax中已經描述。以下設置為全局非常有用:
timeout
(默認: 0
):對Ajax請求設置一個非零的值指定一個默認的超時時間,以毫秒為單位。
global
(默認: true):設置為false。以防止觸發Ajax事件。
xhr
(默認:XMLHttpRequest factory):設置為一個函數,它返回XMLHttpRequest實例(或一個兼容的對象)
accepts
: 從服務器請求的MIME類型,指定dataType
值:
- script: “text/javascript, application/javascript”
- json: “application/json”
- xml: “application/xml, text/xml”
- html: “text/html”
- text: “text/plain”
$.get
$.get(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.get(url, [data], [function(data, status, xhr){ ... }], [dataType]) ⇒ XMLHttpRequest v1.0+
執行一個Ajax GET請求。這是一個 $.ajax的簡寫方式。
$.get('/whatevs.html', function(response){
$(document.body).append(response)
})
$.getJSON
$.getJSON(url, function(data, status, xhr){ ... }) ⇒ XMLHttpRequest
$.getJSON(url, [data], function(data, status, xhr){ ... }) ⇒ XMLHttpRequest v1.0+
通過 Ajax GET請求獲取JSON數據。這是一個 $.ajax 的簡寫方式。
$.getJSON('/awesome.json', function(data){
console.log(data)
})
// fetch data from another domain with JSONP
$.getJSON('//example.com/awesome.json?callback=?', function(remoteData){
console.log(remoteData)
})
$.param
$.param(object, [shallow]) ⇒ string
$.param(array) ⇒ string
序列化一個對象,在Ajax請求中提交的數據使用URL編碼的查詢字符串表示形式。如果shallow設置為true。嵌套對象不會被序列化,嵌套數組的值不會使用放括號在他們的key上。
如果任何對象的某個屬性值是一個函數,而不是一個字符串,該函數將被調用並且返回值後才會被序列化。
此外,還接受 serializeArray格式的數組,其中每個項都有 “name” 和 “value”屬性。
$.param({ foo: { one: 1, two: 2 }})
//=> "foo[one]=1&foo[two]=2)"
$.param({ ids: [1,2,3] })
//=> "ids[]=1&ids[]=2&ids[]=3"
$.param({ ids: [1,2,3] }, true)
//=> "ids=1&ids=2&ids=3"
$.param({ foo: 'bar', nested: { will: 'not be ignored' }})
//=> "foo=bar&nested[will]=not+be+ignored"
$.param({ foo: 'bar', nested: { will: 'be ignored' }}, true)
//=> "foo=bar&nested=[object+Object]"
$.param({ id: function(){ return 1 + 2 } })
//=> "id=3"
$.post
$.post(url, [data], function(data, status, xhr){ ... }, [dataType]) ⇒ XMLHttpRequest
執行Ajax POST請求。這是一個 $.ajax 的簡寫方式。
$.post('/create', { sample: 'payload' }, function(response){
// process response
})
data
參數可以是一個字符串:
$.post('/create', $('#some_form').serialize(), function(response){
// ...
})
load
load(url, function(data, status, xhr){ ... }) ⇒ self
通過GET Ajax載入遠程 HTML 內容代碼並插入至 當前的集合 中。另外,一個css選擇器可以在url中指定,像這樣,可以使用匹配selector選擇器的HTML內容來更新集合。
$('#some_element').load('/foo.html #bar')
如果沒有給定CSS選擇器,將使用完整的返回文本。
請注意,在沒有選擇器的情況下,任何javascript塊都會執行。如果帶上選擇器,匹配選擇器內的script將會被刪除。
serialize
serialize() ⇒ string
在Ajax post請求中將用作提交的表單元素的值編譯成 URL編碼的 字符串。
serializeArray
serializeArray() ⇒ array
將用作提交的表單元素的值編譯成擁有name
和value
對象組成的數組。不能使用的表單元素,buttons,未選中的radio buttons/checkboxs 將會被跳過。結果不包含file inputs的數據。
$('form').serializeArray()
//=> [{ name: 'size', value: 'micro' },
// { name: 'name', value: 'Zepto' }]
submit
submit() ⇒ self
submit(function(e){ ... }) ⇒ self
為 "submit" 事件綁定一個處理函數,或者觸發元素上的 "submit" 事件。當沒有給定function參數時,觸發當前表單“submit”事件,並且執行默認的提交表單行為,除非調用了
preventDefault()
。
當給定function參數時,在當前元素上它簡單得為其在“submit”事件綁定一個處理函數。
Effects
$.fx
全局地動畫設置:
改變現有值或者添加一個新屬性去影響使用一個字符串來設置時間的動畫。
animate
animate(properties, [duration, [easing, [function(){ ... }]]]) ⇒ self
animate(properties, { duration: msec, easing: type, complete: fn }) ⇒ self
animate(animationName, { ... }) ⇒ self
對當前對象集合中元素進行css transition屬性平滑過渡。
properties
: 一個對象,該對象包含了css動畫的值,或者css幀動畫的名稱。
duration
(默認 400):以毫秒為單位的時間,或者一個字符串。
easing
(默認 linear
):指定動畫的緩動類型,使用以下一個:
complete
:動畫完成時的回調函數
li>delay
: 以毫秒為單位的過度延遲時間
v1.1+
Zepto 還支持以下 CSS transform 屬性:
translate(X|Y|Z|3d)
rotate(X|Y|Z|3d)
scale(X|Y|Z)
matrix(3d)
perspective
skew(X|Y)
如果duration參數為 0
或
$.fx.off
為 true(在不支持css transitions的瀏覽器中默認為true),動畫將不被執行;替代動畫效果的目標位置會即刻生效。類似的,如果指定的動畫不是通過動畫完成,而且動畫的目標位置即可生效。這種情況下沒有動畫,
complete
方法也不會被調用。
如果第一個參數是字符串而不是一個對象,它將被當作一個css關鍵幀動畫 CSS
keyframe animation的名稱。
$("#some_element").animate({
opacity: 0.25,
left:
'50px',
color:
'#abcdef',
rotateZ:
'45deg',
translate3d: '0,10px,0'
}, 500,
'ease-out')
Zepto隻使用css過渡效果的動畫。jquery的easings不會支持。jquery的相對變化("=+10px") syntax 也不支持。請查看
list of animatable properties。瀏覽器的支持可能不同,所以一定要測試你所想要支持的瀏覽器。
Touch
Touch events
“touch”模塊添加以下事件,可以使用 on 和 off。
tap
—元素tap的時候觸發。
singleTap
and doubleTap
— 這一對事件可以用來檢測元素上的單擊和雙擊。(如果你不需要檢測單擊、雙擊,使用
tap
代替)。
longTap
— 當一個元素被按住超過750ms觸發。
swipe
, swipeLeft
, swipeRight
, swipeUp
,
swipeDown
— 當元素被劃過時觸發。(可選擇給定的方向)
這些事件也是所有Zepto對象集合上的快捷方法。
<style>.delete { display: none; }</style>
<ul id=items>
<li>List item 1 <span class=delete>DELETE</span></li>
<li>List item 2 <span class=delete>DELETE</span></li>
</ul>
<script>
// show delete buttons on swipe
$('#items li').swipe(function(){
$('.delete').hide()
$('.delete', this).show()
})
// delete row on tapping delete button
$('.delete').tap(function(){
$(this).parent('li').remove()
})
</script>
Change Log
v1.1.0
— 05 Dec 2013
— diff
Notable changes
- IE10+ support
- Huge speed optimizations for simple CSS selectors (classname, ID) and DOM element creation
- Provide
$.Callbacks
and $.Deferred
in optional modules
- Removed
fx
and detect
modules from default build
Ajax
- New supported
$.ajax()
options:
xhrFields
mimeType
jsonpCallback
username
& password
- Promise interface supported when loading the optional “callbacks” and “deferred” modules:
xhr.done(function(data, status, xhr){ ... })
xhr.fail(function(xhr, errorType, error){ ... })
xhr.always(function(){ ... })
- Enable mutating Ajax settings in the
beforeSend
callback
- Fix JSONP callbacks for errored responses on Android
- Ensure consistent
Accept
request HTTP header across browsers
- Fix
$.param()
for jQuery compatibility when handling complex nested objects
- Support IIS JavaScript MIME type
- Pass “abort” and “timeout” status to global
ajaxError
event handlers
Event
- Provide
isDefaultPrevented()
, stopImmediatePropagation()
, and related methods for all events
- Support the
data
argument in .bind()
, .on()
, and .one()
- Support CSS selector argument in
.one()
for event delegation
- Support
.on('ready')
as an alias for .ready()
- Enable event handlers on plain old JS objects
- Many fixes related to event delegation
Data
- Cleanup
.data()
values on DOM element removal with .remove/empty()
.data()
now assumes that numbers that begin with zeroes are strings
.removeData()
(no argument) now removes all data on the element
- Enable reading
data-*
attributes that have underscores in the name
Misc.
- Support simple DOM property names in
.prop(name)
such as for
, class
, readonly
…
- Implement the
.scrollLeft([value])
method
- Support setting
.scrollTop(value)
- Fix
$(document).width/height()
- Support fetching multiple CSS values via array in
.css(['prop1', 'prop2', ...])
- Support setting CSS transition delay via
delay
option for .animate()
- Ensure that
.animate()
callback always firesParty like it’s one-oh!_
v1.0
— 02 Mar 2013
— diff
Party like it’s one-oh!
Notable changes
- Zepto is now compatible with Twitter Bootstrap
- Portable, completely new node.js-based build system
- Fully automated tests with PhantomJS and Travis CI
- Removed
touch
module from default distribution
New features
$.fn.filter(function(index){ ... })
$.fn.contents()
$.fn.wrapInner()
$.fn.scrollTop()
$.contains()
$.fn.has()
$.fn.position()
$.fn.offsetParent()
$.parseJSON()
$.camelCase()
$.isWindow()
$.grep()
(interface to Array.filter
)
- Support
$(html, attributes)
syntax for element creation
- Emulate
mouseenter
and mouseleave
events
- Bootstrap compat: support
$.fn.offset(coordinates)
- Bootstrap compat: implement
$.fn.detach()
- Add support for Ajax
cache: false
option
- Prevent scrolling when horizontal swipe events are detected
cancelTouch
for tap events
prev
and next
now support an optional selector argument
$.fn.find
and $.fn.closest
now support Zepto objects as arguments
- Enable deep copy via
$.extend(true, target, source)
- Enable nested structures for
$.fn.wrap()
and $.fn.wrapAll()
- Enable function arguments for
$.fn.wrap()
and $.fn.wrapInner()
- Support number, boolean, JSON types in data attributes
- Support manipulating classnames on SVG elements
- Enable named durations for
animate
, e.g. slow
.
- Support
timing-function
for animate
- Support event properties passed to
$.fn.trigger()
or $.Event()
- Selector module: support child
> *
queries
- Add detect support for mobile Chrome browser
- Add
$.os.phone
and $.os.tablet
(booleans)
- Detect Firefox mobile, Playbooks and BB10
Fixes
- Fix passing null selector to
on
or off
- Fixed bug where self-closing html tags would act as open tags
- Fix
val
for multiple select
- Fix various touch and gesture bugs.
- Corrected parameters of
load
success callback to match jQuery.
- Fix
css
with 0 values and falsy values
- Fix a
css
performance issues with string values
- Fix
$.ajaxJSONP
when invoked directly
- Fix
animate
with 0 durations.
- Fix
toggle
and fadeToggle
for multiple elements.
- Fix ajax
$.fn.load
behavior with selector
- Make
attr(name, null)
unset attribute
- Fix
animate
in Firefox
- Fix
animate
for elements just added to DOM
- Fix an escaping issue with
$.param
- Respect
traditional: true
option in $.ajax
- Fix
focus
& blur
event delegation and enable unbind
- Simple wrapping for any object passed to
$()
- Enable
children
method for XML documents
- Don’t eval
<script>
content when src
is present
- Support
processData
option for $.ajax()
- Enable passing
contentType: false
to $.ajax()
- Apply
focus()
and blur()
to all elements in collection
- Change
$.fn.map()
to return a Zepto collection
- Selector argument for
on(evt, selector, fn)
can be false
- Don’t raise error on
$('#')
- Provide empty object in
$.support
return false
in event handler calls stopPropagation()
- Fix
$.isPlainObject()
for window
in Opera
$.ajax
error callback correctly reports abort
status
- Fix
hasClass
in collections of multiple elements
- Stop iteration in
each()
when the callback returns false
- Add ability to set
xhr
factory per-request
- Have
get()
method accept negative index
- Support for multiple class names in
toggleClass()
- Fix error callbacks for
ajaxJSONP
- Support optional
data
argument for various Ajax methods
- Fix DOM insertion operators for null values
- Fix dataType being set for
$.getJSON
v1.0rc1
— 09 Apr 2012
— diff
The semicolon-free edition! That’s right, we removed all trailing semicolons
from the source and tests. They were never needed anyway.
New methods:
New module:
- “selector.js” with experimental support for jQuery CSS
pseudo-selectors such as
:visible
and :first
Improvements in core:
- added missing methods for Ember.js compatibility
- improved creating DOM fragments from HTML with $()
- enable append & family to accept multiple arguments
- fix $.each context
- fix calling get without index
- fix calling val on empty collection
- using
css(property, '')
removes the property
- fix filter, is, and closest when operating on
nodes that are detached from the document
- remove
end
& andSelf
from core to the new “stack.js” plugin
- exposed important internal Zepto functions through the
$.zepto
object for
extending or overriding Zepto functionality.
- data method returns undefined when there is no data
- support camelized names in data method
Apart from improving the basic data
method in core, the “data.js” module got
improvements as well:
- better jQuery compatibility
- ability to store functions
- new
removeData
method
Ajax:
- have correct ajaxComplete argument order for JSONP abort and timeout
- JSONP requests that hit a 404 will now correctly invoke the error callback
- add support for
dataType: 'jsonp'
in $.ajax
- add support for
data
in $.ajaxJSONP
- HTTP 304 status is treated as success instead of an error
- made load more compatible with jQuery
- allow Content-Type to be set via request headers
- respect Content-Type of the response if
dataType
isn’t set
- work around Chrome CORS bug when data is empty
Changes in other modules:
- fix animate for edge cases such as when there is an animation
within an animated element, and improve handling of transition CSS properties
- new “singleTap” event
- improved “longTap” detection
0.8
— 03 Nov 2011
— diff
- CSS transitions for every browser with
animate()
method;
- unified event handling with
fn.on()
& off()
;
- Ajax global events & timeout support;
- performance boost for selectors.
See full release notes.
0.7
— 01 Aug 2011
— diff
- add
$.each
, $.map
, $.slice
;
- add
.serializeArray()
, .serialize()
;
- add
.triggerHandler()
;
- add
.wrap
, .wrapAll
, .unwrap
, .width/height
setters, .append
(and
friends) improvements;
- add “longTap” event;
.anim()
accepts CSS transform properties;
return false
in event handlers cancels browser event behavior.
0.6
— 14 May 2011
— diff
- add
.add
, .appendTo
, .prependTo
, .replaceWith
, .empty
, .submit
;
- allow function args for
.add/.remove/.toggleClass
;
- improvements to events and xhr.
0.5
— 01 Mar 2011
— diff
- add
.not
, .children
, .siblings
, $.param
;
- improve
.attr
& .html
;
- support callback for
.anim
.
0.4
— 21 Jan 2011
— diff
- JSONP;
- better
.find
, .each
, .closest
;
- add
.eq
, .size
, .parent
, .parents
, .removeAttr
, .val
;
- support function args in
.html
, .attr
;
- adjacency methods now take Zepto objects.
0.3
— 17 Dec 2010
— diff
- add
.toggleClass
, .attr
setter, .last
, .undelegate
, .die
;
- proxied event objects for event delegation;
- support
$
fragments.
0.2
— 01 Dec 2010
— diff
- now compatible with backbone.js;
- support event unbind;
- ajax posts with data.
0.1
— 26 Oct 2010
First. Release. Ever.
Acknowledgements & Thanks
A big Thank-You goes out to all of our
awesome Zepto.js contributors.
May you all forever bask in glory.
The Zepto API is based on jQuery's Core API, which
is released under the MIT license.
This documentation is based on the layout of the
Backbone.js
documentation, which is released under the
MIT license.
© 2010-2014 Thomas Fuchs, Freckle Online Time Tracking
Zepto and this documentation is released under the terms of the MIT license.