Zepto.js + selector

Zepto.js 增加了 selector 模块

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/32445/212976/Zeptojs%20%2B%20selector.js

  1. /* Zepto 1.2.0 - zepto event ajax form ie selector - zeptojs.com/license */
  2. (function(global, factory) {
  3. if (typeof define === 'function' && define.amd)
  4. define(function() { return factory(global) })
  5. else
  6. factory(global)
  7. }(window, function(window) {
  8. var Zepto = (function() {
  9. var undefined, key, $, classList, emptyArray = [], concat = emptyArray.concat, filter = emptyArray.filter, slice = emptyArray.slice,
  10. document = window.document,
  11. elementDisplay = {}, classCache = {},
  12. cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
  13. fragmentRE = /^\s*<(\w+|!)[^>]*>/,
  14. singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
  15. tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
  16. rootNodeRE = /^(?:body|html)$/i,
  17. capitalRE = /([A-Z])/g,
  18.  
  19. // special attributes that should be get/set via method calls
  20. methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
  21.  
  22. adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
  23. table = document.createElement('table'),
  24. tableRow = document.createElement('tr'),
  25. containers = {
  26. 'tr': document.createElement('tbody'),
  27. 'tbody': table, 'thead': table, 'tfoot': table,
  28. 'td': tableRow, 'th': tableRow,
  29. '*': document.createElement('div')
  30. },
  31. simpleSelectorRE = /^[\w-]*$/,
  32. class2type = {},
  33. toString = class2type.toString,
  34. zepto = {},
  35. camelize, uniq,
  36. tempParent = document.createElement('div'),
  37. propMap = {
  38. 'tabindex': 'tabIndex',
  39. 'readonly': 'readOnly',
  40. 'for': 'htmlFor',
  41. 'class': 'className',
  42. 'maxlength': 'maxLength',
  43. 'cellspacing': 'cellSpacing',
  44. 'cellpadding': 'cellPadding',
  45. 'rowspan': 'rowSpan',
  46. 'colspan': 'colSpan',
  47. 'usemap': 'useMap',
  48. 'frameborder': 'frameBorder',
  49. 'contenteditable': 'contentEditable'
  50. },
  51. isArray = Array.isArray ||
  52. function(object){ return object instanceof Array }
  53.  
  54. zepto.matches = function(element, selector) {
  55. if (!selector || !element || element.nodeType !== 1) return false
  56. var matchesSelector = element.matches || element.webkitMatchesSelector ||
  57. element.mozMatchesSelector || element.oMatchesSelector ||
  58. element.matchesSelector
  59. if (matchesSelector) return matchesSelector.call(element, selector)
  60. // fall back to performing a selector:
  61. var match, parent = element.parentNode, temp = !parent
  62. if (temp) (parent = tempParent).appendChild(element)
  63. match = ~zepto.qsa(parent, selector).indexOf(element)
  64. temp && tempParent.removeChild(element)
  65. return match
  66. }
  67.  
  68. function type(obj) {
  69. return obj == null ? String(obj) :
  70. class2type[toString.call(obj)] || "object"
  71. }
  72.  
  73. function isFunction(value) { return type(value) == "function" }
  74. function isWindow(obj) { return obj != null && obj == obj.window }
  75. function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
  76. function isObject(obj) { return type(obj) == "object" }
  77. function isPlainObject(obj) {
  78. return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
  79. }
  80.  
  81. function likeArray(obj) {
  82. var length = !!obj && 'length' in obj && obj.length,
  83. type = $.type(obj)
  84.  
  85. return 'function' != type && !isWindow(obj) && (
  86. 'array' == type || length === 0 ||
  87. (typeof length == 'number' && length > 0 && (length - 1) in obj)
  88. )
  89. }
  90.  
  91. function compact(array) { return filter.call(array, function(item){ return item != null }) }
  92. function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
  93. camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
  94. function dasherize(str) {
  95. return str.replace(/::/g, '/')
  96. .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
  97. .replace(/([a-z\d])([A-Z])/g, '$1_$2')
  98. .replace(/_/g, '-')
  99. .toLowerCase()
  100. }
  101. uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
  102.  
  103. function classRE(name) {
  104. return name in classCache ?
  105. classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
  106. }
  107.  
  108. function maybeAddPx(name, value) {
  109. return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
  110. }
  111.  
  112. function defaultDisplay(nodeName) {
  113. var element, display
  114. if (!elementDisplay[nodeName]) {
  115. element = document.createElement(nodeName)
  116. document.body.appendChild(element)
  117. display = getComputedStyle(element, '').getPropertyValue("display")
  118. element.parentNode.removeChild(element)
  119. display == "none" && (display = "block")
  120. elementDisplay[nodeName] = display
  121. }
  122. return elementDisplay[nodeName]
  123. }
  124.  
  125. function children(element) {
  126. return 'children' in element ?
  127. slice.call(element.children) :
  128. $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
  129. }
  130.  
  131. function Z(dom, selector) {
  132. var i, len = dom ? dom.length : 0
  133. for (i = 0; i < len; i++) this[i] = dom[i]
  134. this.length = len
  135. this.selector = selector || ''
  136. }
  137.  
  138. // `$.zepto.fragment` takes a html string and an optional tag name
  139. // to generate DOM nodes from the given html string.
  140. // The generated DOM nodes are returned as an array.
  141. // This function can be overridden in plugins for example to make
  142. // it compatible with browsers that don't support the DOM fully.
  143. zepto.fragment = function(html, name, properties) {
  144. var dom, nodes, container
  145.  
  146. // A special case optimization for a single tag
  147. if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
  148.  
  149. if (!dom) {
  150. if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
  151. if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
  152. if (!(name in containers)) name = '*'
  153.  
  154. container = containers[name]
  155. container.innerHTML = '' + html
  156. dom = $.each(slice.call(container.childNodes), function(){
  157. container.removeChild(this)
  158. })
  159. }
  160.  
  161. if (isPlainObject(properties)) {
  162. nodes = $(dom)
  163. $.each(properties, function(key, value) {
  164. if (methodAttributes.indexOf(key) > -1) nodes[key](value)
  165. else nodes.attr(key, value)
  166. })
  167. }
  168.  
  169. return dom
  170. }
  171.  
  172. // `$.zepto.Z` swaps out the prototype of the given `dom` array
  173. // of nodes with `$.fn` and thus supplying all the Zepto functions
  174. // to the array. This method can be overridden in plugins.
  175. zepto.Z = function(dom, selector) {
  176. return new Z(dom, selector)
  177. }
  178.  
  179. // `$.zepto.isZ` should return `true` if the given object is a Zepto
  180. // collection. This method can be overridden in plugins.
  181. zepto.isZ = function(object) {
  182. return object instanceof zepto.Z
  183. }
  184.  
  185. // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
  186. // takes a CSS selector and an optional context (and handles various
  187. // special cases).
  188. // This method can be overridden in plugins.
  189. zepto.init = function(selector, context) {
  190. var dom
  191. // If nothing given, return an empty Zepto collection
  192. if (!selector) return zepto.Z()
  193. // Optimize for string selectors
  194. else if (typeof selector == 'string') {
  195. selector = selector.trim()
  196. // If it's a html fragment, create nodes from it
  197. // Note: In both Chrome 21 and Firefox 15, DOM error 12
  198. // is thrown if the fragment doesn't begin with <
  199. if (selector[0] == '<' && fragmentRE.test(selector))
  200. dom = zepto.fragment(selector, RegExp.$1, context), selector = null
  201. // If there's a context, create a collection on that context first, and select
  202. // nodes from there
  203. else if (context !== undefined) return $(context).find(selector)
  204. // If it's a CSS selector, use it to select nodes.
  205. else dom = zepto.qsa(document, selector)
  206. }
  207. // If a function is given, call it when the DOM is ready
  208. else if (isFunction(selector)) return $(document).ready(selector)
  209. // If a Zepto collection is given, just return it
  210. else if (zepto.isZ(selector)) return selector
  211. else {
  212. // normalize array if an array of nodes is given
  213. if (isArray(selector)) dom = compact(selector)
  214. // Wrap DOM nodes.
  215. else if (isObject(selector))
  216. dom = [selector], selector = null
  217. // If it's a html fragment, create nodes from it
  218. else if (fragmentRE.test(selector))
  219. dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
  220. // If there's a context, create a collection on that context first, and select
  221. // nodes from there
  222. else if (context !== undefined) return $(context).find(selector)
  223. // And last but no least, if it's a CSS selector, use it to select nodes.
  224. else dom = zepto.qsa(document, selector)
  225. }
  226. // create a new Zepto collection from the nodes found
  227. return zepto.Z(dom, selector)
  228. }
  229.  
  230. // `$` will be the base `Zepto` object. When calling this
  231. // function just call `$.zepto.init, which makes the implementation
  232. // details of selecting nodes and creating Zepto collections
  233. // patchable in plugins.
  234. $ = function(selector, context){
  235. return zepto.init(selector, context)
  236. }
  237.  
  238. function extend(target, source, deep) {
  239. for (key in source)
  240. if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
  241. if (isPlainObject(source[key]) && !isPlainObject(target[key]))
  242. target[key] = {}
  243. if (isArray(source[key]) && !isArray(target[key]))
  244. target[key] = []
  245. extend(target[key], source[key], deep)
  246. }
  247. else if (source[key] !== undefined) target[key] = source[key]
  248. }
  249.  
  250. // Copy all but undefined properties from one or more
  251. // objects to the `target` object.
  252. $.extend = function(target){
  253. var deep, args = slice.call(arguments, 1)
  254. if (typeof target == 'boolean') {
  255. deep = target
  256. target = args.shift()
  257. }
  258. args.forEach(function(arg){ extend(target, arg, deep) })
  259. return target
  260. }
  261.  
  262. // `$.zepto.qsa` is Zepto's CSS selector implementation which
  263. // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
  264. // This method can be overridden in plugins.
  265. zepto.qsa = function(element, selector){
  266. var found,
  267. maybeID = selector[0] == '#',
  268. maybeClass = !maybeID && selector[0] == '.',
  269. nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
  270. isSimple = simpleSelectorRE.test(nameOnly)
  271. return (element.getElementById && isSimple && maybeID) ? // Safari DocumentFragment doesn't have getElementById
  272. ( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
  273. (element.nodeType !== 1 && element.nodeType !== 9 && element.nodeType !== 11) ? [] :
  274. slice.call(
  275. isSimple && !maybeID && element.getElementsByClassName ? // DocumentFragment doesn't have getElementsByClassName/TagName
  276. maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
  277. element.getElementsByTagName(selector) : // Or a tag
  278. element.querySelectorAll(selector) // Or it's not simple, and we need to query all
  279. )
  280. }
  281.  
  282. function filtered(nodes, selector) {
  283. return selector == null ? $(nodes) : $(nodes).filter(selector)
  284. }
  285.  
  286. $.contains = document.documentElement.contains ?
  287. function(parent, node) {
  288. return parent !== node && parent.contains(node)
  289. } :
  290. function(parent, node) {
  291. while (node && (node = node.parentNode))
  292. if (node === parent) return true
  293. return false
  294. }
  295.  
  296. function funcArg(context, arg, idx, payload) {
  297. return isFunction(arg) ? arg.call(context, idx, payload) : arg
  298. }
  299.  
  300. function setAttribute(node, name, value) {
  301. value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
  302. }
  303.  
  304. // access className property while respecting SVGAnimatedString
  305. function className(node, value){
  306. var klass = node.className || '',
  307. svg = klass && klass.baseVal !== undefined
  308.  
  309. if (value === undefined) return svg ? klass.baseVal : klass
  310. svg ? (klass.baseVal = value) : (node.className = value)
  311. }
  312.  
  313. // "true" => true
  314. // "false" => false
  315. // "null" => null
  316. // "42" => 42
  317. // "42.5" => 42.5
  318. // "08" => "08"
  319. // JSON => parse if valid
  320. // String => self
  321. function deserializeValue(value) {
  322. try {
  323. return value ?
  324. value == "true" ||
  325. ( value == "false" ? false :
  326. value == "null" ? null :
  327. +value + "" == value ? +value :
  328. /^[\[\{]/.test(value) ? $.parseJSON(value) :
  329. value )
  330. : value
  331. } catch(e) {
  332. return value
  333. }
  334. }
  335.  
  336. $.type = type
  337. $.isFunction = isFunction
  338. $.isWindow = isWindow
  339. $.isArray = isArray
  340. $.isPlainObject = isPlainObject
  341.  
  342. $.isEmptyObject = function(obj) {
  343. var name
  344. for (name in obj) return false
  345. return true
  346. }
  347.  
  348. $.isNumeric = function(val) {
  349. var num = Number(val), type = typeof val
  350. return val != null && type != 'boolean' &&
  351. (type != 'string' || val.length) &&
  352. !isNaN(num) && isFinite(num) || false
  353. }
  354.  
  355. $.inArray = function(elem, array, i){
  356. return emptyArray.indexOf.call(array, elem, i)
  357. }
  358.  
  359. $.camelCase = camelize
  360. $.trim = function(str) {
  361. return str == null ? "" : String.prototype.trim.call(str)
  362. }
  363.  
  364. // plugin compatibility
  365. $.uuid = 0
  366. $.support = { }
  367. $.expr = { }
  368. $.noop = function() {}
  369.  
  370. $.map = function(elements, callback){
  371. var value, values = [], i, key
  372. if (likeArray(elements))
  373. for (i = 0; i < elements.length; i++) {
  374. value = callback(elements[i], i)
  375. if (value != null) values.push(value)
  376. }
  377. else
  378. for (key in elements) {
  379. value = callback(elements[key], key)
  380. if (value != null) values.push(value)
  381. }
  382. return flatten(values)
  383. }
  384.  
  385. $.each = function(elements, callback){
  386. var i, key
  387. if (likeArray(elements)) {
  388. for (i = 0; i < elements.length; i++)
  389. if (callback.call(elements[i], i, elements[i]) === false) return elements
  390. } else {
  391. for (key in elements)
  392. if (callback.call(elements[key], key, elements[key]) === false) return elements
  393. }
  394.  
  395. return elements
  396. }
  397.  
  398. $.grep = function(elements, callback){
  399. return filter.call(elements, callback)
  400. }
  401.  
  402. if (window.JSON) $.parseJSON = JSON.parse
  403.  
  404. // Populate the class2type map
  405. $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
  406. class2type[ "[object " + name + "]" ] = name.toLowerCase()
  407. })
  408.  
  409. // Define methods that will be available on all
  410. // Zepto collections
  411. $.fn = {
  412. constructor: zepto.Z,
  413. length: 0,
  414.  
  415. // Because a collection acts like an array
  416. // copy over these useful array functions.
  417. forEach: emptyArray.forEach,
  418. reduce: emptyArray.reduce,
  419. push: emptyArray.push,
  420. sort: emptyArray.sort,
  421. splice: emptyArray.splice,
  422. indexOf: emptyArray.indexOf,
  423. concat: function(){
  424. var i, value, args = []
  425. for (i = 0; i < arguments.length; i++) {
  426. value = arguments[i]
  427. args[i] = zepto.isZ(value) ? value.toArray() : value
  428. }
  429. return concat.apply(zepto.isZ(this) ? this.toArray() : this, args)
  430. },
  431.  
  432. // `map` and `slice` in the jQuery API work differently
  433. // from their array counterparts
  434. map: function(fn){
  435. return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
  436. },
  437. slice: function(){
  438. return $(slice.apply(this, arguments))
  439. },
  440.  
  441. ready: function(callback){
  442. // don't use "interactive" on IE <= 10 (it can fired premature)
  443. if (document.readyState === "complete" ||
  444. (document.readyState !== "loading" && !document.documentElement.doScroll))
  445. setTimeout(function(){ callback($) }, 0)
  446. else {
  447. var handler = function() {
  448. document.removeEventListener("DOMContentLoaded", handler, false)
  449. window.removeEventListener("load", handler, false)
  450. callback($)
  451. }
  452. document.addEventListener("DOMContentLoaded", handler, false)
  453. window.addEventListener("load", handler, false)
  454. }
  455. return this
  456. },
  457. get: function(idx){
  458. return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
  459. },
  460. toArray: function(){ return this.get() },
  461. size: function(){
  462. return this.length
  463. },
  464. remove: function(){
  465. return this.each(function(){
  466. if (this.parentNode != null)
  467. this.parentNode.removeChild(this)
  468. })
  469. },
  470. each: function(callback){
  471. emptyArray.every.call(this, function(el, idx){
  472. return callback.call(el, idx, el) !== false
  473. })
  474. return this
  475. },
  476. filter: function(selector){
  477. if (isFunction(selector)) return this.not(this.not(selector))
  478. return $(filter.call(this, function(element){
  479. return zepto.matches(element, selector)
  480. }))
  481. },
  482. add: function(selector,context){
  483. return $(uniq(this.concat($(selector,context))))
  484. },
  485. is: function(selector){
  486. return typeof selector == 'string' ? this.length > 0 && zepto.matches(this[0], selector) :
  487. selector && this.selector == selector.selector
  488. },
  489. not: function(selector){
  490. var nodes=[]
  491. if (isFunction(selector) && selector.call !== undefined)
  492. this.each(function(idx){
  493. if (!selector.call(this,idx)) nodes.push(this)
  494. })
  495. else {
  496. var excludes = typeof selector == 'string' ? this.filter(selector) :
  497. (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
  498. this.forEach(function(el){
  499. if (excludes.indexOf(el) < 0) nodes.push(el)
  500. })
  501. }
  502. return $(nodes)
  503. },
  504. has: function(selector){
  505. return this.filter(function(){
  506. return isObject(selector) ?
  507. $.contains(this, selector) :
  508. $(this).find(selector).size()
  509. })
  510. },
  511. eq: function(idx){
  512. return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
  513. },
  514. first: function(){
  515. var el = this[0]
  516. return el && !isObject(el) ? el : $(el)
  517. },
  518. last: function(){
  519. var el = this[this.length - 1]
  520. return el && !isObject(el) ? el : $(el)
  521. },
  522. find: function(selector){
  523. var result, $this = this
  524. if (!selector) result = $()
  525. else if (typeof selector == 'object')
  526. result = $(selector).filter(function(){
  527. var node = this
  528. return emptyArray.some.call($this, function(parent){
  529. return $.contains(parent, node)
  530. })
  531. })
  532. else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
  533. else result = this.map(function(){ return zepto.qsa(this, selector) })
  534. return result
  535. },
  536. closest: function(selector, context){
  537. var nodes = [], collection = typeof selector == 'object' && $(selector)
  538. this.each(function(_, node){
  539. while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
  540. node = node !== context && !isDocument(node) && node.parentNode
  541. if (node && nodes.indexOf(node) < 0) nodes.push(node)
  542. })
  543. return $(nodes)
  544. },
  545. parents: function(selector){
  546. var ancestors = [], nodes = this
  547. while (nodes.length > 0)
  548. nodes = $.map(nodes, function(node){
  549. if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
  550. ancestors.push(node)
  551. return node
  552. }
  553. })
  554. return filtered(ancestors, selector)
  555. },
  556. parent: function(selector){
  557. return filtered(uniq(this.pluck('parentNode')), selector)
  558. },
  559. children: function(selector){
  560. return filtered(this.map(function(){ return children(this) }), selector)
  561. },
  562. contents: function() {
  563. return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })
  564. },
  565. siblings: function(selector){
  566. return filtered(this.map(function(i, el){
  567. return filter.call(children(el.parentNode), function(child){ return child!==el })
  568. }), selector)
  569. },
  570. empty: function(){
  571. return this.each(function(){ this.innerHTML = '' })
  572. },
  573. // `pluck` is borrowed from Prototype.js
  574. pluck: function(property){
  575. return $.map(this, function(el){ return el[property] })
  576. },
  577. show: function(){
  578. return this.each(function(){
  579. this.style.display == "none" && (this.style.display = '')
  580. if (getComputedStyle(this, '').getPropertyValue("display") == "none")
  581. this.style.display = defaultDisplay(this.nodeName)
  582. })
  583. },
  584. replaceWith: function(newContent){
  585. return this.before(newContent).remove()
  586. },
  587. wrap: function(structure){
  588. var func = isFunction(structure)
  589. if (this[0] && !func)
  590. var dom = $(structure).get(0),
  591. clone = dom.parentNode || this.length > 1
  592.  
  593. return this.each(function(index){
  594. $(this).wrapAll(
  595. func ? structure.call(this, index) :
  596. clone ? dom.cloneNode(true) : dom
  597. )
  598. })
  599. },
  600. wrapAll: function(structure){
  601. if (this[0]) {
  602. $(this[0]).before(structure = $(structure))
  603. var children
  604. // drill down to the inmost element
  605. while ((children = structure.children()).length) structure = children.first()
  606. $(structure).append(this)
  607. }
  608. return this
  609. },
  610. wrapInner: function(structure){
  611. var func = isFunction(structure)
  612. return this.each(function(index){
  613. var self = $(this), contents = self.contents(),
  614. dom = func ? structure.call(this, index) : structure
  615. contents.length ? contents.wrapAll(dom) : self.append(dom)
  616. })
  617. },
  618. unwrap: function(){
  619. this.parent().each(function(){
  620. $(this).replaceWith($(this).children())
  621. })
  622. return this
  623. },
  624. clone: function(){
  625. return this.map(function(){ return this.cloneNode(true) })
  626. },
  627. hide: function(){
  628. return this.css("display", "none")
  629. },
  630. toggle: function(setting){
  631. return this.each(function(){
  632. var el = $(this)
  633. ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
  634. })
  635. },
  636. prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
  637. next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
  638. html: function(html){
  639. return 0 in arguments ?
  640. this.each(function(idx){
  641. var originHtml = this.innerHTML
  642. $(this).empty().append( funcArg(this, html, idx, originHtml) )
  643. }) :
  644. (0 in this ? this[0].innerHTML : null)
  645. },
  646. text: function(text){
  647. return 0 in arguments ?
  648. this.each(function(idx){
  649. var newText = funcArg(this, text, idx, this.textContent)
  650. this.textContent = newText == null ? '' : ''+newText
  651. }) :
  652. (0 in this ? this.pluck('textContent').join("") : null)
  653. },
  654. attr: function(name, value){
  655. var result
  656. return (typeof name == 'string' && !(1 in arguments)) ?
  657. (0 in this && this[0].nodeType == 1 && (result = this[0].getAttribute(name)) != null ? result : undefined) :
  658. this.each(function(idx){
  659. if (this.nodeType !== 1) return
  660. if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
  661. else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
  662. })
  663. },
  664. removeAttr: function(name){
  665. return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){
  666. setAttribute(this, attribute)
  667. }, this)})
  668. },
  669. prop: function(name, value){
  670. name = propMap[name] || name
  671. return (typeof name == 'string' && !(1 in arguments)) ?
  672. (this[0] && this[0][name]) :
  673. this.each(function(idx){
  674. if (isObject(name)) for (key in name) this[propMap[key] || key] = name[key]
  675. else this[name] = funcArg(this, value, idx, this[name])
  676. })
  677. },
  678. removeProp: function(name){
  679. name = propMap[name] || name
  680. return this.each(function(){ delete this[name] })
  681. },
  682. data: function(name, value){
  683. var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase()
  684.  
  685. var data = (1 in arguments) ?
  686. this.attr(attrName, value) :
  687. this.attr(attrName)
  688.  
  689. return data !== null ? deserializeValue(data) : undefined
  690. },
  691. val: function(value){
  692. if (0 in arguments) {
  693. if (value == null) value = ""
  694. return this.each(function(idx){
  695. this.value = funcArg(this, value, idx, this.value)
  696. })
  697. } else {
  698. return this[0] && (this[0].multiple ?
  699. $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
  700. this[0].value)
  701. }
  702. },
  703. offset: function(coordinates){
  704. if (coordinates) return this.each(function(index){
  705. var $this = $(this),
  706. coords = funcArg(this, coordinates, index, $this.offset()),
  707. parentOffset = $this.offsetParent().offset(),
  708. props = {
  709. top: coords.top - parentOffset.top,
  710. left: coords.left - parentOffset.left
  711. }
  712.  
  713. if ($this.css('position') == 'static') props['position'] = 'relative'
  714. $this.css(props)
  715. })
  716. if (!this.length) return null
  717. if (document.documentElement !== this[0] && !$.contains(document.documentElement, this[0]))
  718. return {top: 0, left: 0}
  719. var obj = this[0].getBoundingClientRect()
  720. return {
  721. left: obj.left + window.pageXOffset,
  722. top: obj.top + window.pageYOffset,
  723. width: Math.round(obj.width),
  724. height: Math.round(obj.height)
  725. }
  726. },
  727. css: function(property, value){
  728. if (arguments.length < 2) {
  729. var element = this[0]
  730. if (typeof property == 'string') {
  731. if (!element) return
  732. return element.style[camelize(property)] || getComputedStyle(element, '').getPropertyValue(property)
  733. } else if (isArray(property)) {
  734. if (!element) return
  735. var props = {}
  736. var computedStyle = getComputedStyle(element, '')
  737. $.each(property, function(_, prop){
  738. props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
  739. })
  740. return props
  741. }
  742. }
  743.  
  744. var css = ''
  745. if (type(property) == 'string') {
  746. if (!value && value !== 0)
  747. this.each(function(){ this.style.removeProperty(dasherize(property)) })
  748. else
  749. css = dasherize(property) + ":" + maybeAddPx(property, value)
  750. } else {
  751. for (key in property)
  752. if (!property[key] && property[key] !== 0)
  753. this.each(function(){ this.style.removeProperty(dasherize(key)) })
  754. else
  755. css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
  756. }
  757.  
  758. return this.each(function(){ this.style.cssText += ';' + css })
  759. },
  760. index: function(element){
  761. return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
  762. },
  763. hasClass: function(name){
  764. if (!name) return false
  765. return emptyArray.some.call(this, function(el){
  766. return this.test(className(el))
  767. }, classRE(name))
  768. },
  769. addClass: function(name){
  770. if (!name) return this
  771. return this.each(function(idx){
  772. if (!('className' in this)) return
  773. classList = []
  774. var cls = className(this), newName = funcArg(this, name, idx, cls)
  775. newName.split(/\s+/g).forEach(function(klass){
  776. if (!$(this).hasClass(klass)) classList.push(klass)
  777. }, this)
  778. classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
  779. })
  780. },
  781. removeClass: function(name){
  782. return this.each(function(idx){
  783. if (!('className' in this)) return
  784. if (name === undefined) return className(this, '')
  785. classList = className(this)
  786. funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
  787. classList = classList.replace(classRE(klass), " ")
  788. })
  789. className(this, classList.trim())
  790. })
  791. },
  792. toggleClass: function(name, when){
  793. if (!name) return this
  794. return this.each(function(idx){
  795. var $this = $(this), names = funcArg(this, name, idx, className(this))
  796. names.split(/\s+/g).forEach(function(klass){
  797. (when === undefined ? !$this.hasClass(klass) : when) ?
  798. $this.addClass(klass) : $this.removeClass(klass)
  799. })
  800. })
  801. },
  802. scrollTop: function(value){
  803. if (!this.length) return
  804. var hasScrollTop = 'scrollTop' in this[0]
  805. if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
  806. return this.each(hasScrollTop ?
  807. function(){ this.scrollTop = value } :
  808. function(){ this.scrollTo(this.scrollX, value) })
  809. },
  810. scrollLeft: function(value){
  811. if (!this.length) return
  812. var hasScrollLeft = 'scrollLeft' in this[0]
  813. if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
  814. return this.each(hasScrollLeft ?
  815. function(){ this.scrollLeft = value } :
  816. function(){ this.scrollTo(value, this.scrollY) })
  817. },
  818. position: function() {
  819. if (!this.length) return
  820.  
  821. var elem = this[0],
  822. // Get *real* offsetParent
  823. offsetParent = this.offsetParent(),
  824. // Get correct offsets
  825. offset = this.offset(),
  826. parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
  827.  
  828. // Subtract element margins
  829. // note: when an element has margin: auto the offsetLeft and marginLeft
  830. // are the same in Safari causing offset.left to incorrectly be 0
  831. offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
  832. offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
  833.  
  834. // Add offsetParent borders
  835. parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
  836. parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
  837.  
  838. // Subtract the two offsets
  839. return {
  840. top: offset.top - parentOffset.top,
  841. left: offset.left - parentOffset.left
  842. }
  843. },
  844. offsetParent: function() {
  845. return this.map(function(){
  846. var parent = this.offsetParent || document.body
  847. while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
  848. parent = parent.offsetParent
  849. return parent
  850. })
  851. }
  852. }
  853.  
  854. // for now
  855. $.fn.detach = $.fn.remove
  856.  
  857. // Generate the `width` and `height` functions
  858. ;['width', 'height'].forEach(function(dimension){
  859. var dimensionProperty =
  860. dimension.replace(/./, function(m){ return m[0].toUpperCase() })
  861.  
  862. $.fn[dimension] = function(value){
  863. var offset, el = this[0]
  864. if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
  865. isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
  866. (offset = this.offset()) && offset[dimension]
  867. else return this.each(function(idx){
  868. el = $(this)
  869. el.css(dimension, funcArg(this, value, idx, el[dimension]()))
  870. })
  871. }
  872. })
  873.  
  874. function traverseNode(node, fun) {
  875. fun(node)
  876. for (var i = 0, len = node.childNodes.length; i < len; i++)
  877. traverseNode(node.childNodes[i], fun)
  878. }
  879.  
  880. // Generate the `after`, `prepend`, `before`, `append`,
  881. // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
  882. adjacencyOperators.forEach(function(operator, operatorIndex) {
  883. var inside = operatorIndex % 2 //=> prepend, append
  884.  
  885. $.fn[operator] = function(){
  886. // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
  887. var argType, nodes = $.map(arguments, function(arg) {
  888. var arr = []
  889. argType = type(arg)
  890. if (argType == "array") {
  891. arg.forEach(function(el) {
  892. if (el.nodeType !== undefined) return arr.push(el)
  893. else if ($.zepto.isZ(el)) return arr = arr.concat(el.get())
  894. arr = arr.concat(zepto.fragment(el))
  895. })
  896. return arr
  897. }
  898. return argType == "object" || arg == null ?
  899. arg : zepto.fragment(arg)
  900. }),
  901. parent, copyByClone = this.length > 1
  902. if (nodes.length < 1) return this
  903.  
  904. return this.each(function(_, target){
  905. parent = inside ? target : target.parentNode
  906.  
  907. // convert all methods to a "before" operation
  908. target = operatorIndex == 0 ? target.nextSibling :
  909. operatorIndex == 1 ? target.firstChild :
  910. operatorIndex == 2 ? target :
  911. null
  912.  
  913. var parentInDocument = $.contains(document.documentElement, parent)
  914.  
  915. nodes.forEach(function(node){
  916. if (copyByClone) node = node.cloneNode(true)
  917. else if (!parent) return $(node).remove()
  918.  
  919. parent.insertBefore(node, target)
  920. if (parentInDocument) traverseNode(node, function(el){
  921. if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
  922. (!el.type || el.type === 'text/javascript') && !el.src){
  923. var target = el.ownerDocument ? el.ownerDocument.defaultView : window
  924. target['eval'].call(target, el.innerHTML)
  925. }
  926. })
  927. })
  928. })
  929. }
  930.  
  931. // after => insertAfter
  932. // prepend => prependTo
  933. // before => insertBefore
  934. // append => appendTo
  935. $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
  936. $(html)[operator](this)
  937. return this
  938. }
  939. })
  940.  
  941. zepto.Z.prototype = Z.prototype = $.fn
  942.  
  943. // Export internal API functions in the `$.zepto` namespace
  944. zepto.uniq = uniq
  945. zepto.deserializeValue = deserializeValue
  946. $.zepto = zepto
  947.  
  948. return $
  949. })()
  950.  
  951. window.Zepto = Zepto
  952. window.$ === undefined && (window.$ = Zepto)
  953.  
  954. ;(function($){
  955. var _zid = 1, undefined,
  956. slice = Array.prototype.slice,
  957. isFunction = $.isFunction,
  958. isString = function(obj){ return typeof obj == 'string' },
  959. handlers = {},
  960. specialEvents={},
  961. focusinSupported = 'onfocusin' in window,
  962. focus = { focus: 'focusin', blur: 'focusout' },
  963. hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
  964.  
  965. specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
  966.  
  967. function zid(element) {
  968. return element._zid || (element._zid = _zid++)
  969. }
  970. function findHandlers(element, event, fn, selector) {
  971. event = parse(event)
  972. if (event.ns) var matcher = matcherFor(event.ns)
  973. return (handlers[zid(element)] || []).filter(function(handler) {
  974. return handler
  975. && (!event.e || handler.e == event.e)
  976. && (!event.ns || matcher.test(handler.ns))
  977. && (!fn || zid(handler.fn) === zid(fn))
  978. && (!selector || handler.sel == selector)
  979. })
  980. }
  981. function parse(event) {
  982. var parts = ('' + event).split('.')
  983. return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
  984. }
  985. function matcherFor(ns) {
  986. return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
  987. }
  988.  
  989. function eventCapture(handler, captureSetting) {
  990. return handler.del &&
  991. (!focusinSupported && (handler.e in focus)) ||
  992. !!captureSetting
  993. }
  994.  
  995. function realEvent(type) {
  996. return hover[type] || (focusinSupported && focus[type]) || type
  997. }
  998.  
  999. function add(element, events, fn, data, selector, delegator, capture){
  1000. var id = zid(element), set = (handlers[id] || (handlers[id] = []))
  1001. events.split(/\s/).forEach(function(event){
  1002. if (event == 'ready') return $(document).ready(fn)
  1003. var handler = parse(event)
  1004. handler.fn = fn
  1005. handler.sel = selector
  1006. // emulate mouseenter, mouseleave
  1007. if (handler.e in hover) fn = function(e){
  1008. var related = e.relatedTarget
  1009. if (!related || (related !== this && !$.contains(this, related)))
  1010. return handler.fn.apply(this, arguments)
  1011. }
  1012. handler.del = delegator
  1013. var callback = delegator || fn
  1014. handler.proxy = function(e){
  1015. e = compatible(e)
  1016. if (e.isImmediatePropagationStopped()) return
  1017. e.data = data
  1018. var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
  1019. if (result === false) e.preventDefault(), e.stopPropagation()
  1020. return result
  1021. }
  1022. handler.i = set.length
  1023. set.push(handler)
  1024. if ('addEventListener' in element)
  1025. element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
  1026. })
  1027. }
  1028. function remove(element, events, fn, selector, capture){
  1029. var id = zid(element)
  1030. ;(events || '').split(/\s/).forEach(function(event){
  1031. findHandlers(element, event, fn, selector).forEach(function(handler){
  1032. delete handlers[id][handler.i]
  1033. if ('removeEventListener' in element)
  1034. element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
  1035. })
  1036. })
  1037. }
  1038.  
  1039. $.event = { add: add, remove: remove }
  1040.  
  1041. $.proxy = function(fn, context) {
  1042. var args = (2 in arguments) && slice.call(arguments, 2)
  1043. if (isFunction(fn)) {
  1044. var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) }
  1045. proxyFn._zid = zid(fn)
  1046. return proxyFn
  1047. } else if (isString(context)) {
  1048. if (args) {
  1049. args.unshift(fn[context], fn)
  1050. return $.proxy.apply(null, args)
  1051. } else {
  1052. return $.proxy(fn[context], fn)
  1053. }
  1054. } else {
  1055. throw new TypeError("expected function")
  1056. }
  1057. }
  1058.  
  1059. $.fn.bind = function(event, data, callback){
  1060. return this.on(event, data, callback)
  1061. }
  1062. $.fn.unbind = function(event, callback){
  1063. return this.off(event, callback)
  1064. }
  1065. $.fn.one = function(event, selector, data, callback){
  1066. return this.on(event, selector, data, callback, 1)
  1067. }
  1068.  
  1069. var returnTrue = function(){return true},
  1070. returnFalse = function(){return false},
  1071. ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,
  1072. eventMethods = {
  1073. preventDefault: 'isDefaultPrevented',
  1074. stopImmediatePropagation: 'isImmediatePropagationStopped',
  1075. stopPropagation: 'isPropagationStopped'
  1076. }
  1077.  
  1078. function compatible(event, source) {
  1079. if (source || !event.isDefaultPrevented) {
  1080. source || (source = event)
  1081.  
  1082. $.each(eventMethods, function(name, predicate) {
  1083. var sourceMethod = source[name]
  1084. event[name] = function(){
  1085. this[predicate] = returnTrue
  1086. return sourceMethod && sourceMethod.apply(source, arguments)
  1087. }
  1088. event[predicate] = returnFalse
  1089. })
  1090.  
  1091. try {
  1092. event.timeStamp || (event.timeStamp = Date.now())
  1093. } catch (ignored) { }
  1094.  
  1095. if (source.defaultPrevented !== undefined ? source.defaultPrevented :
  1096. 'returnValue' in source ? source.returnValue === false :
  1097. source.getPreventDefault && source.getPreventDefault())
  1098. event.isDefaultPrevented = returnTrue
  1099. }
  1100. return event
  1101. }
  1102.  
  1103. function createProxy(event) {
  1104. var key, proxy = { originalEvent: event }
  1105. for (key in event)
  1106. if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
  1107.  
  1108. return compatible(proxy, event)
  1109. }
  1110.  
  1111. $.fn.delegate = function(selector, event, callback){
  1112. return this.on(event, selector, callback)
  1113. }
  1114. $.fn.undelegate = function(selector, event, callback){
  1115. return this.off(event, selector, callback)
  1116. }
  1117.  
  1118. $.fn.live = function(event, callback){
  1119. $(document.body).delegate(this.selector, event, callback)
  1120. return this
  1121. }
  1122. $.fn.die = function(event, callback){
  1123. $(document.body).undelegate(this.selector, event, callback)
  1124. return this
  1125. }
  1126.  
  1127. $.fn.on = function(event, selector, data, callback, one){
  1128. var autoRemove, delegator, $this = this
  1129. if (event && !isString(event)) {
  1130. $.each(event, function(type, fn){
  1131. $this.on(type, selector, data, fn, one)
  1132. })
  1133. return $this
  1134. }
  1135.  
  1136. if (!isString(selector) && !isFunction(callback) && callback !== false)
  1137. callback = data, data = selector, selector = undefined
  1138. if (callback === undefined || data === false)
  1139. callback = data, data = undefined
  1140.  
  1141. if (callback === false) callback = returnFalse
  1142.  
  1143. return $this.each(function(_, element){
  1144. if (one) autoRemove = function(e){
  1145. remove(element, e.type, callback)
  1146. return callback.apply(this, arguments)
  1147. }
  1148.  
  1149. if (selector) delegator = function(e){
  1150. var evt, match = $(e.target).closest(selector, element).get(0)
  1151. if (match && match !== element) {
  1152. evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
  1153. return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
  1154. }
  1155. }
  1156.  
  1157. add(element, event, callback, data, selector, delegator || autoRemove)
  1158. })
  1159. }
  1160. $.fn.off = function(event, selector, callback){
  1161. var $this = this
  1162. if (event && !isString(event)) {
  1163. $.each(event, function(type, fn){
  1164. $this.off(type, selector, fn)
  1165. })
  1166. return $this
  1167. }
  1168.  
  1169. if (!isString(selector) && !isFunction(callback) && callback !== false)
  1170. callback = selector, selector = undefined
  1171.  
  1172. if (callback === false) callback = returnFalse
  1173.  
  1174. return $this.each(function(){
  1175. remove(this, event, callback, selector)
  1176. })
  1177. }
  1178.  
  1179. $.fn.trigger = function(event, args){
  1180. event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
  1181. event._args = args
  1182. return this.each(function(){
  1183. // handle focus(), blur() by calling them directly
  1184. if (event.type in focus && typeof this[event.type] == "function") this[event.type]()
  1185. // items in the collection might not be DOM elements
  1186. else if ('dispatchEvent' in this) this.dispatchEvent(event)
  1187. else $(this).triggerHandler(event, args)
  1188. })
  1189. }
  1190.  
  1191. // triggers event handlers on current element just as if an event occurred,
  1192. // doesn't trigger an actual event, doesn't bubble
  1193. $.fn.triggerHandler = function(event, args){
  1194. var e, result
  1195. this.each(function(i, element){
  1196. e = createProxy(isString(event) ? $.Event(event) : event)
  1197. e._args = args
  1198. e.target = element
  1199. $.each(findHandlers(element, event.type || event), function(i, handler){
  1200. result = handler.proxy(e)
  1201. if (e.isImmediatePropagationStopped()) return false
  1202. })
  1203. })
  1204. return result
  1205. }
  1206.  
  1207. // shortcut methods for `.bind(event, fn)` for each event type
  1208. ;('focusin focusout focus blur load resize scroll unload click dblclick '+
  1209. 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
  1210. 'change select keydown keypress keyup error').split(' ').forEach(function(event) {
  1211. $.fn[event] = function(callback) {
  1212. return (0 in arguments) ?
  1213. this.bind(event, callback) :
  1214. this.trigger(event)
  1215. }
  1216. })
  1217.  
  1218. $.Event = function(type, props) {
  1219. if (!isString(type)) props = type, type = props.type
  1220. var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
  1221. if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
  1222. event.initEvent(type, bubbles, true)
  1223. return compatible(event)
  1224. }
  1225.  
  1226. })(Zepto)
  1227.  
  1228. ;(function($){
  1229. var jsonpID = +new Date(),
  1230. document = window.document,
  1231. key,
  1232. name,
  1233. rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
  1234. scriptTypeRE = /^(?:text|application)\/javascript/i,
  1235. xmlTypeRE = /^(?:text|application)\/xml/i,
  1236. jsonType = 'application/json',
  1237. htmlType = 'text/html',
  1238. blankRE = /^\s*$/,
  1239. originAnchor = document.createElement('a')
  1240.  
  1241. originAnchor.href = window.location.href
  1242.  
  1243. // trigger a custom event and return false if it was cancelled
  1244. function triggerAndReturn(context, eventName, data) {
  1245. var event = $.Event(eventName)
  1246. $(context).trigger(event, data)
  1247. return !event.isDefaultPrevented()
  1248. }
  1249.  
  1250. // trigger an Ajax "global" event
  1251. function triggerGlobal(settings, context, eventName, data) {
  1252. if (settings.global) return triggerAndReturn(context || document, eventName, data)
  1253. }
  1254.  
  1255. // Number of active Ajax requests
  1256. $.active = 0
  1257.  
  1258. function ajaxStart(settings) {
  1259. if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
  1260. }
  1261. function ajaxStop(settings) {
  1262. if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
  1263. }
  1264.  
  1265. // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
  1266. function ajaxBeforeSend(xhr, settings) {
  1267. var context = settings.context
  1268. if (settings.beforeSend.call(context, xhr, settings) === false ||
  1269. triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
  1270. return false
  1271.  
  1272. triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
  1273. }
  1274. function ajaxSuccess(data, xhr, settings, deferred) {
  1275. var context = settings.context, status = 'success'
  1276. settings.success.call(context, data, status, xhr)
  1277. if (deferred) deferred.resolveWith(context, [data, status, xhr])
  1278. triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
  1279. ajaxComplete(status, xhr, settings)
  1280. }
  1281. // type: "timeout", "error", "abort", "parsererror"
  1282. function ajaxError(error, type, xhr, settings, deferred) {
  1283. var context = settings.context
  1284. settings.error.call(context, xhr, type, error)
  1285. if (deferred) deferred.rejectWith(context, [xhr, type, error])
  1286. triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
  1287. ajaxComplete(type, xhr, settings)
  1288. }
  1289. // status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
  1290. function ajaxComplete(status, xhr, settings) {
  1291. var context = settings.context
  1292. settings.complete.call(context, xhr, status)
  1293. triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
  1294. ajaxStop(settings)
  1295. }
  1296.  
  1297. function ajaxDataFilter(data, type, settings) {
  1298. if (settings.dataFilter == empty) return data
  1299. var context = settings.context
  1300. return settings.dataFilter.call(context, data, type)
  1301. }
  1302.  
  1303. // Empty function, used as default callback
  1304. function empty() {}
  1305.  
  1306. $.ajaxJSONP = function(options, deferred){
  1307. if (!('type' in options)) return $.ajax(options)
  1308.  
  1309. var _callbackName = options.jsonpCallback,
  1310. callbackName = ($.isFunction(_callbackName) ?
  1311. _callbackName() : _callbackName) || ('Zepto' + (jsonpID++)),
  1312. script = document.createElement('script'),
  1313. originalCallback = window[callbackName],
  1314. responseData,
  1315. abort = function(errorType) {
  1316. $(script).triggerHandler('error', errorType || 'abort')
  1317. },
  1318. xhr = { abort: abort }, abortTimeout
  1319.  
  1320. if (deferred) deferred.promise(xhr)
  1321.  
  1322. $(script).on('load error', function(e, errorType){
  1323. clearTimeout(abortTimeout)
  1324. $(script).off().remove()
  1325.  
  1326. if (e.type == 'error' || !responseData) {
  1327. ajaxError(null, errorType || 'error', xhr, options, deferred)
  1328. } else {
  1329. ajaxSuccess(responseData[0], xhr, options, deferred)
  1330. }
  1331.  
  1332. window[callbackName] = originalCallback
  1333. if (responseData && $.isFunction(originalCallback))
  1334. originalCallback(responseData[0])
  1335.  
  1336. originalCallback = responseData = undefined
  1337. })
  1338.  
  1339. if (ajaxBeforeSend(xhr, options) === false) {
  1340. abort('abort')
  1341. return xhr
  1342. }
  1343.  
  1344. window[callbackName] = function(){
  1345. responseData = arguments
  1346. }
  1347.  
  1348. script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName)
  1349. document.head.appendChild(script)
  1350.  
  1351. if (options.timeout > 0) abortTimeout = setTimeout(function(){
  1352. abort('timeout')
  1353. }, options.timeout)
  1354.  
  1355. return xhr
  1356. }
  1357.  
  1358. $.ajaxSettings = {
  1359. // Default type of request
  1360. type: 'GET',
  1361. // Callback that is executed before request
  1362. beforeSend: empty,
  1363. // Callback that is executed if the request succeeds
  1364. success: empty,
  1365. // Callback that is executed the the server drops error
  1366. error: empty,
  1367. // Callback that is executed on request complete (both: error and success)
  1368. complete: empty,
  1369. // The context for the callbacks
  1370. context: null,
  1371. // Whether to trigger "global" Ajax events
  1372. global: true,
  1373. // Transport
  1374. xhr: function () {
  1375. return new window.XMLHttpRequest()
  1376. },
  1377. // MIME types mapping
  1378. // IIS returns Javascript as "application/x-javascript"
  1379. accepts: {
  1380. script: 'text/javascript, application/javascript, application/x-javascript',
  1381. json: jsonType,
  1382. xml: 'application/xml, text/xml',
  1383. html: htmlType,
  1384. text: 'text/plain'
  1385. },
  1386. // Whether the request is to another domain
  1387. crossDomain: false,
  1388. // Default timeout
  1389. timeout: 0,
  1390. // Whether data should be serialized to string
  1391. processData: true,
  1392. // Whether the browser should be allowed to cache GET responses
  1393. cache: true,
  1394. //Used to handle the raw response data of XMLHttpRequest.
  1395. //This is a pre-filtering function to sanitize the response.
  1396. //The sanitized response should be returned
  1397. dataFilter: empty
  1398. }
  1399.  
  1400. function mimeToDataType(mime) {
  1401. if (mime) mime = mime.split(';', 2)[0]
  1402. return mime && ( mime == htmlType ? 'html' :
  1403. mime == jsonType ? 'json' :
  1404. scriptTypeRE.test(mime) ? 'script' :
  1405. xmlTypeRE.test(mime) && 'xml' ) || 'text'
  1406. }
  1407.  
  1408. function appendQuery(url, query) {
  1409. if (query == '') return url
  1410. return (url + '&' + query).replace(/[&?]{1,2}/, '?')
  1411. }
  1412.  
  1413. // serialize payload and append it to the URL for GET requests
  1414. function serializeData(options) {
  1415. if (options.processData && options.data && $.type(options.data) != "string")
  1416. options.data = $.param(options.data, options.traditional)
  1417. if (options.data && (!options.type || options.type.toUpperCase() == 'GET' || 'jsonp' == options.dataType))
  1418. options.url = appendQuery(options.url, options.data), options.data = undefined
  1419. }
  1420.  
  1421. $.ajax = function(options){
  1422. var settings = $.extend({}, options || {}),
  1423. deferred = $.Deferred && $.Deferred(),
  1424. urlAnchor, hashIndex
  1425. for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]
  1426.  
  1427. ajaxStart(settings)
  1428.  
  1429. if (!settings.crossDomain) {
  1430. urlAnchor = document.createElement('a')
  1431. urlAnchor.href = settings.url
  1432. // cleans up URL for .href (IE only), see https://github.com/madrobby/zepto/pull/1049
  1433. urlAnchor.href = urlAnchor.href
  1434. settings.crossDomain = (originAnchor.protocol + '//' + originAnchor.host) !== (urlAnchor.protocol + '//' + urlAnchor.host)
  1435. }
  1436.  
  1437. if (!settings.url) settings.url = window.location.toString()
  1438. if ((hashIndex = settings.url.indexOf('#')) > -1) settings.url = settings.url.slice(0, hashIndex)
  1439. serializeData(settings)
  1440.  
  1441. var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url)
  1442. if (hasPlaceholder) dataType = 'jsonp'
  1443.  
  1444. if (settings.cache === false || (
  1445. (!options || options.cache !== true) &&
  1446. ('script' == dataType || 'jsonp' == dataType)
  1447. ))
  1448. settings.url = appendQuery(settings.url, '_=' + Date.now())
  1449.  
  1450. if ('jsonp' == dataType) {
  1451. if (!hasPlaceholder)
  1452. settings.url = appendQuery(settings.url,
  1453. settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
  1454. return $.ajaxJSONP(settings, deferred)
  1455. }
  1456.  
  1457. var mime = settings.accepts[dataType],
  1458. headers = { },
  1459. setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
  1460. protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
  1461. xhr = settings.xhr(),
  1462. nativeSetHeader = xhr.setRequestHeader,
  1463. abortTimeout
  1464.  
  1465. if (deferred) deferred.promise(xhr)
  1466.  
  1467. if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest')
  1468. setHeader('Accept', mime || '*/*')
  1469. if (mime = settings.mimeType || mime) {
  1470. if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
  1471. xhr.overrideMimeType && xhr.overrideMimeType(mime)
  1472. }
  1473. if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
  1474. setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')
  1475.  
  1476. if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
  1477. xhr.setRequestHeader = setHeader
  1478.  
  1479. xhr.onreadystatechange = function(){
  1480. if (xhr.readyState == 4) {
  1481. xhr.onreadystatechange = empty
  1482. clearTimeout(abortTimeout)
  1483. var result, error = false
  1484. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
  1485. dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
  1486.  
  1487. if (xhr.responseType == 'arraybuffer' || xhr.responseType == 'blob')
  1488. result = xhr.response
  1489. else {
  1490. result = xhr.responseText
  1491.  
  1492. try {
  1493. // http://perfectionkills.com/global-eval-what-are-the-options/
  1494. // sanitize response accordingly if data filter callback provided
  1495. result = ajaxDataFilter(result, dataType, settings)
  1496. if (dataType == 'script') (1,eval)(result)
  1497. else if (dataType == 'xml') result = xhr.responseXML
  1498. else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
  1499. } catch (e) { error = e }
  1500.  
  1501. if (error) return ajaxError(error, 'parsererror', xhr, settings, deferred)
  1502. }
  1503.  
  1504. ajaxSuccess(result, xhr, settings, deferred)
  1505. } else {
  1506. ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred)
  1507. }
  1508. }
  1509. }
  1510.  
  1511. if (ajaxBeforeSend(xhr, settings) === false) {
  1512. xhr.abort()
  1513. ajaxError(null, 'abort', xhr, settings, deferred)
  1514. return xhr
  1515. }
  1516.  
  1517. var async = 'async' in settings ? settings.async : true
  1518. xhr.open(settings.type, settings.url, async, settings.username, settings.password)
  1519.  
  1520. if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]
  1521.  
  1522. for (name in headers) nativeSetHeader.apply(xhr, headers[name])
  1523.  
  1524. if (settings.timeout > 0) abortTimeout = setTimeout(function(){
  1525. xhr.onreadystatechange = empty
  1526. xhr.abort()
  1527. ajaxError(null, 'timeout', xhr, settings, deferred)
  1528. }, settings.timeout)
  1529.  
  1530. // avoid sending empty string (#319)
  1531. xhr.send(settings.data ? settings.data : null)
  1532. return xhr
  1533. }
  1534.  
  1535. // handle optional data/success arguments
  1536. function parseArguments(url, data, success, dataType) {
  1537. if ($.isFunction(data)) dataType = success, success = data, data = undefined
  1538. if (!$.isFunction(success)) dataType = success, success = undefined
  1539. return {
  1540. url: url
  1541. , data: data
  1542. , success: success
  1543. , dataType: dataType
  1544. }
  1545. }
  1546.  
  1547. $.get = function(/* url, data, success, dataType */){
  1548. return $.ajax(parseArguments.apply(null, arguments))
  1549. }
  1550.  
  1551. $.post = function(/* url, data, success, dataType */){
  1552. var options = parseArguments.apply(null, arguments)
  1553. options.type = 'POST'
  1554. return $.ajax(options)
  1555. }
  1556.  
  1557. $.getJSON = function(/* url, data, success */){
  1558. var options = parseArguments.apply(null, arguments)
  1559. options.dataType = 'json'
  1560. return $.ajax(options)
  1561. }
  1562.  
  1563. $.fn.load = function(url, data, success){
  1564. if (!this.length) return this
  1565. var self = this, parts = url.split(/\s/), selector,
  1566. options = parseArguments(url, data, success),
  1567. callback = options.success
  1568. if (parts.length > 1) options.url = parts[0], selector = parts[1]
  1569. options.success = function(response){
  1570. self.html(selector ?
  1571. $('<div>').html(response.replace(rscript, "")).find(selector)
  1572. : response)
  1573. callback && callback.apply(self, arguments)
  1574. }
  1575. $.ajax(options)
  1576. return this
  1577. }
  1578.  
  1579. var escape = encodeURIComponent
  1580.  
  1581. function serialize(params, obj, traditional, scope){
  1582. var type, array = $.isArray(obj), hash = $.isPlainObject(obj)
  1583. $.each(obj, function(key, value) {
  1584. type = $.type(value)
  1585. if (scope) key = traditional ? scope :
  1586. scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'
  1587. // handle data in serializeArray() format
  1588. if (!scope && array) params.add(value.name, value.value)
  1589. // recurse into nested objects
  1590. else if (type == "array" || (!traditional && type == "object"))
  1591. serialize(params, value, traditional, key)
  1592. else params.add(key, value)
  1593. })
  1594. }
  1595.  
  1596. $.param = function(obj, traditional){
  1597. var params = []
  1598. params.add = function(key, value) {
  1599. if ($.isFunction(value)) value = value()
  1600. if (value == null) value = ""
  1601. this.push(escape(key) + '=' + escape(value))
  1602. }
  1603. serialize(params, obj, traditional)
  1604. return params.join('&').replace(/%20/g, '+')
  1605. }
  1606. })(Zepto)
  1607.  
  1608. ;(function($){
  1609. $.fn.serializeArray = function() {
  1610. var name, type, result = [],
  1611. add = function(value) {
  1612. if (value.forEach) return value.forEach(add)
  1613. result.push({ name: name, value: value })
  1614. }
  1615. if (this[0]) $.each(this[0].elements, function(_, field){
  1616. type = field.type, name = field.name
  1617. if (name && field.nodeName.toLowerCase() != 'fieldset' &&
  1618. !field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' &&
  1619. ((type != 'radio' && type != 'checkbox') || field.checked))
  1620. add($(field).val())
  1621. })
  1622. return result
  1623. }
  1624.  
  1625. $.fn.serialize = function(){
  1626. var result = []
  1627. this.serializeArray().forEach(function(elm){
  1628. result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
  1629. })
  1630. return result.join('&')
  1631. }
  1632.  
  1633. $.fn.submit = function(callback) {
  1634. if (0 in arguments) this.bind('submit', callback)
  1635. else if (this.length) {
  1636. var event = $.Event('submit')
  1637. this.eq(0).trigger(event)
  1638. if (!event.isDefaultPrevented()) this.get(0).submit()
  1639. }
  1640. return this
  1641. }
  1642.  
  1643. })(Zepto)
  1644.  
  1645. ;(function(){
  1646. // getComputedStyle shouldn't freak out when called
  1647. // without a valid element as argument
  1648. try {
  1649. getComputedStyle(undefined)
  1650. } catch(e) {
  1651. var nativeGetComputedStyle = getComputedStyle
  1652. window.getComputedStyle = function(element, pseudoElement){
  1653. try {
  1654. return nativeGetComputedStyle(element, pseudoElement)
  1655. } catch(e) {
  1656. return null
  1657. }
  1658. }
  1659. }
  1660. })()
  1661.  
  1662. ;(function($){
  1663. var zepto = $.zepto, oldQsa = zepto.qsa, oldMatches = zepto.matches
  1664.  
  1665. function visible(elem){
  1666. elem = $(elem)
  1667. return !!(elem.width() || elem.height()) && elem.css("display") !== "none"
  1668. }
  1669.  
  1670. // Implements a subset from:
  1671. // http://api.jquery.com/category/selectors/jquery-selector-extensions/
  1672. //
  1673. // Each filter function receives the current index, all nodes in the
  1674. // considered set, and a value if there were parentheses. The value
  1675. // of `this` is the node currently being considered. The function returns the
  1676. // resulting node(s), null, or undefined.
  1677. //
  1678. // Complex selectors are not supported:
  1679. // li:has(label:contains("foo")) + li:has(label:contains("bar"))
  1680. // ul.inner:first > li
  1681. var filters = $.expr[':'] = {
  1682. visible: function(){ if (visible(this)) return this },
  1683. hidden: function(){ if (!visible(this)) return this },
  1684. selected: function(){ if (this.selected) return this },
  1685. checked: function(){ if (this.checked) return this },
  1686. parent: function(){ return this.parentNode },
  1687. first: function(idx){ if (idx === 0) return this },
  1688. last: function(idx, nodes){ if (idx === nodes.length - 1) return this },
  1689. eq: function(idx, _, value){ if (idx === value) return this },
  1690. contains: function(idx, _, text){ if ($(this).text().indexOf(text) > -1) return this },
  1691. has: function(idx, _, sel){ if (zepto.qsa(this, sel).length) return this }
  1692. }
  1693.  
  1694. var filterRe = new RegExp('(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*'),
  1695. childRe = /^\s*>/,
  1696. classTag = 'Zepto' + (+new Date())
  1697.  
  1698. function process(sel, fn) {
  1699. // quote the hash in `a[href^=#]` expression
  1700. sel = sel.replace(/=#\]/g, '="#"]')
  1701. var filter, arg, match = filterRe.exec(sel)
  1702. if (match && match[2] in filters) {
  1703. filter = filters[match[2]], arg = match[3]
  1704. sel = match[1]
  1705. if (arg) {
  1706. var num = Number(arg)
  1707. if (isNaN(num)) arg = arg.replace(/^["']|["']$/g, '')
  1708. else arg = num
  1709. }
  1710. }
  1711. return fn(sel, filter, arg)
  1712. }
  1713.  
  1714. zepto.qsa = function(node, selector) {
  1715. return process(selector, function(sel, filter, arg){
  1716. try {
  1717. var taggedParent
  1718. if (!sel && filter) sel = '*'
  1719. else if (childRe.test(sel))
  1720. // support "> *" child queries by tagging the parent node with a
  1721. // unique class and prepending that classname onto the selector
  1722. taggedParent = $(node).addClass(classTag), sel = '.'+classTag+' '+sel
  1723.  
  1724. var nodes = oldQsa(node, sel)
  1725. } catch(e) {
  1726. console.error('error performing selector: %o', selector)
  1727. throw e
  1728. } finally {
  1729. if (taggedParent) taggedParent.removeClass(classTag)
  1730. }
  1731. return !filter ? nodes :
  1732. zepto.uniq($.map(nodes, function(n, i){ return filter.call(n, i, nodes, arg) }))
  1733. })
  1734. }
  1735.  
  1736. zepto.matches = function(node, selector){
  1737. return process(selector, function(sel, filter, arg){
  1738. return (!sel || oldMatches(node, sel)) &&
  1739. (!filter || filter.call(node, null, arg) === node)
  1740. })
  1741. }
  1742. })(Zepto)
  1743. return Zepto
  1744. }));