项目源码: http://jsbin.com/cuzimuf/edit?html,js,output
绑定jQuery
jQuery
函数通常使用jQuery()
的方法获取元素, jQuery
通常用$
代替. 可以通过下面的代码解决
//将jQuery添加到window中
window.jQuery
//将$指向jQuery
window.$ = jQuery
将jQuery
和$
添加到window
的属性当中, 再将$
指向jQuery
. 则$
和jQuery
等价. 为啥要将$
指向jQuery
呢? 因为书写方便, 程序员肯定喜欢写精简的呀!
设置jQuery()
我们可以给jQuery
属性赋一个方法, 这样我们就可以调用jQuery(selector)
方法了.
window.jQuery = function(nodeOrSelector) {
let nodes = {}
//some codes
return nodes
}
应为$
指向了jQuery, 那么我们也可以使用$(selector)
方法. 我们无法确定会返回单个节点还是多个节点, 则返回一个nodes
伪数组模拟即可.
$()
方法要么接收一个节点, 要么接收一个css选择器. 那么我们就需要判断传入的参数. 当传入的参数为css选择器时, 可以使用querySelectorAll()
方法
function(nodeOrSelector) {
var nodes = {}
if (typeof nodeOrSelector === 'string') {
//接收选择器参数
nodes = document.querySelectorAll(nodeOrSelector )
} else if (nodeOrSelector instanceof Node) {
//接收节点参数
nodes = {0:nodeOrSelector, length: 1}
}
return nodes
}
添加方法
我们还可以通过jQuery
返回的对象进行其他操作, 如添加类名, 设置文本等
var $li = $('ul > li') //通过jQuer方法获得的对象我们通常在变量前加$以示区分
$li.addClass('red') //添加类名
$li.setText('选项') //设置文本
若想实现上述方法, 我们只需在jQuery
的函数中添加方法即可.
window.jQuery = function(nodeOrSelector) {
//前面代码省略
nodes.addClass = function(className) {
//some codes
}
nodes.setText = function(text) {
//some codes
}
return nodes
}
因为nodes
是一个伪数组(对象), 那么我们需要遍历nodes
才能设置每一个节点.
window.jQuery = function(nodeOrSelector) {
nodes.addClass = function(className) {
for(let i = 0; i < nodes.length; i++) {
//为每一个节点添加类名
nodes[i].classList.add(className)
}
}
nodes.setText = function(text) {
for(let i = 0; i < nodes.length; i++) {
//为每一个节点设置文本
nodes[i].textContent = text
}
}
}
这样, 我们就可以用我们的addClass()
和setText()
方法了.