zepto.init = function(selector, context) {var dom
// 参数没内容,则返回空集合if (!selector) return zepto.Z()
elseif (typeof selector == 'string') {
selector = selector.trim()
// 如果是 html 标签,则生成 dom 元素// 先行检查是否为 < 开头,提高正则检测效率if (selector[0] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp.$1, context), selector = null// 如果有 context,则生成 context 的对象集合,再检索elseif (context !== undefined) return $(context).find(selector)
// 以 css 规则检索元素else dom = zepto.qsa(document, selector)
}
// 如果传参是函数,则在页面加载完成时触发执行 elseif (isFunction(selector)) return $(document).ready(selector)
// 如果给定的是 zepto 集合,直接返回elseif (zepto.isZ(selector)) return selector
else {
// 是数组,则过滤 null 元素if (isArray(selector)) dom = compact(selector)
// 是对象,则包在数组中elseif (isObject(selector))
dom = [selector], selector = null// If it's a html fragment, create nodes from it// 什么情况下逻辑会走到下面?此时 html fragment 是什么??elseif (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null// If there's a context, create a collection on that context first, and select// nodes from thereelseif (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes foundreturn zepto.Z(dom, selector)
}
zepto.fragment
由给定的 html 字符串生成 DOM 元素
返回由 DOM 元素组成的数组
zepto.fragment = function(html, name, properties) {var dom, nodes, container
// 判断是否空标签,如:<a></a> <p />if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
if (!dom) {
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>") // 补全双标签if (name === undefined) name = fragmentRE.test(html) && RegExp.$1if (!(name in containers)) name = '*'
container = containers[name]
container.innerHTML = '' + html // 使 html 字符串转换成 dom 元素// 将 container 内的元素集合转换成数组,赋值给dom,并清空 container// slice.call 两个好处:1. 转换成数组 2. 数组拷贝// 这里为什么不直接将 container 置空,而是一个个移除呢??
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
}
// properties 属性赋值if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}
return dom
}
zepto.qsa(element, selector)
zepto 下的元素选择器
使用 querySelectorAll 和选项实现类似 css 选择器,如“#id”
不直接用 querySelector 或 querySelectorAll,只为更好的性能
规则
selector 以 # 开头,则用 getElementById
selector 以 . 开头,则用 getElementsByClassName
isSimple=/^[/w-]*$/
isSimple & 非# & 非.,用 getElementsByTagName
非 Simple,用 querySelectorAll
zepto.Z
生成 zepto 对象集合
zepto.Z = function(dom, selector) {returnnew Z(dom, selector)
}
functionZ(dom, selector) {var i, len = dom ? dom.length : 0for (i = 0; i < len; i++) this[i] = dom[i]
this.length = len
this.selector = selector || ''
}