实现一个jQuery的API

发布 : 2019-05-30 分类 : jQuery 浏览 :

1、编写HTML代码

1
2
3
4
5
6
7
8
9
10
11
<body>
<ul>
<li>标签1</li>
<li>标签2</li>
<li>标签3</li>
<li>标签4</li>
<li>标签5</li>
<li>标签6</li>
</ul>
</body>
<script src="./b.js"></script>

2、编写CSS代码

1
2
3
4
5
6
.red {
color: red;
}
.green {
color: green;
}

3、编写JS代码

3.1 修改li标签内容及字体颜色

1
2
3
4
5
6
7
8
let liTags = document.querySelectorAll('ul > li')
for (let i = 0; i < liTags.length; i++) {
liTags[i].classList.add('red')
}

for (let i = 0; i < liTags.length; i++) {
liTags[i].textContent = '修改'
}

3.2 封装为函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function addClass(selector, classes) {
let nodes = document.querySelectorAll(selector)
for (let key in classes) {
let value = classes[key]
if (value) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(key)
}
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(key)
}
}
}
}

function setText(selector, text) {
let nodes = document.querySelectorAll(selector)
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text
}
}
let classes = { 'red': true, 'green': false }
addClass.call(undefined, 'ul>li', classes)
setText.call(undefined, 'ul>li', '封装函数')

3.3 添加命名空间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
window.myDom = {
setClass: function (selector, classes) {
let nodes = document.querySelectorAll(selector)
for (let key in classes) {
let value = classes[key]
if (value) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(key)
}
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(key)
}
}
}
},
setText: function (selector, text) {
let nodes = document.querySelectorAll(selector)
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text
}
}
}
myDom = window.myDom

let classes = { 'red': true, 'green': false }
myDom.setClass.call(undefined, 'ul>li', classes)
myDom.setText.call(undefined, 'ul>li', '添加命名空间')

3.4 最后的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
let jQuery = function (selector) {
let nodes = {}
if (selector) {
nodes = document.querySelectorAll(selector)
}
nodes.setClass = function (classes) {
for (let key in classes) {
let value = classes[key]
if (value) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(key)
}
} else {
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.remove(key)
}
}
}
}
nodes.setText = function (text) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].textContent = text
}
}
return nodes
}
window.jQuery = jQuery
window.$ = jQuery

let classes = { 'red': true, 'green': true }
let $liTags = $('ul>li')
$liTags.setClass.call($liTags, classes)
$liTags.setText.call($liTags, '完成')

4、最后输出样式图

输出样式

本文作者 : LqZww
原文链接 : http://yoursite.com/2019/05/30/shi-xian-yi-ge-jquery-de-api/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!
支付宝扫一扫, 向我赞赏

支付宝扫一扫, 向我赞赏

微信扫一扫, 向我赞赏

微信扫一扫, 向我赞赏

留下足迹