-
Notifications
You must be signed in to change notification settings - Fork 4
/
jQuery之text().html
113 lines (105 loc) · 3.27 KB
/
jQuery之text().html
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery之text()</title>
</head>
<body>
<script src="jQuery.js"></script>
<div class="divOne">
<!--<p id="divTwo">嘿嘿嘿</p>-->
<p>嘿嘿嘿</p>
</div>
<div class="divOne">
<p>哈哈哈</p>
</div>
<input type="text" id="inputOne">
<script>
function readText(elem) {
let node,
ret = "",
i = 0,
nodeType = elem.nodeType
console.log(nodeType,'nodeType22')
//如果selector是类的话,会有多个目标元素,此时需要分别单个循环
//比如document.querySelectorAll('.divOne').nodeType ->undefined
if (!nodeType) {
while ((node = elem[i++])) {
//单个获取
ret += readText(node)
}
}
//元素节点,文档节点,文档碎片
else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
//如果目标元素的内容是文本,则直接返回
if (typeof elem.textContent === "string") {
/*jQuery没有用innerText获取文本的值,http://bugs.jquery.com/ticket/11153,
大概就是在IE8中新节点插入会保留所有回车。
所以jQuery采用了textContent获取文本值,
textContent本身是dom3规范的,可以兼容火狐下的innerText问题。*/
return elem.textContent
}
//如果节点的内容不是文本,则循环子节点,并依次获取它们的文本节点
else {
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += readText(elem)
}
}
}
//文本节点、一个文档的CDATA部分(没遇到过这个)
else if (nodeType === 3 || nodeType === 4) {
//返回节点值
return elem.nodeValue;
}
//nodeType:注释节点 8,处理指令 7
//text()方法不处理这两个类型节点
return ret
}
function customEmpty() {
let elem,
i = 0;
//注意for循环的写法
for (; (elem = this[i]) != null; i++) {
//如果是元素节点的话,清空该节点的所有内容
if (elem.nodeType === 1) {
elem.textContent = "";
}
}
return this;
}
function writeText(value) {
let elem,
i = 0;
//先清空目标元素的内容
customEmpty.call(this)
//循环
for (; (elem = this[i]) != null; i++) {
//元素节点,文档碎片,文档节点
if (elem.nodeType === 1 || elem.nodeType === 11 || elem.nodeType === 9) {
// text()方法不会解析标签
elem.textContent = value;
}
}
//return this 方便链式调用
return this
}
function customText(value) {
return value === undefined ?
//读
readText(this) :
//写
writeText.call(this, value)
}
customText.call(document.querySelectorAll('.divOne'))
customText.call(document.querySelectorAll('.divOne'),"Hello <b>world</b>!")
// let p=document.createElement('p')
// p.innerText='哈哈哈'
console.log($(".divOne").text())
// customText.call(document.querySelectorAll('.divOne'))
// console.log(document.querySelectorAll('.divOne').nodeType,'childnode81')
// console.log(document.querySelectorAll('.divOne')[0].textContent,'childnode81')
// $("#divOne").text('<p>aaaa</p>')
// console.log(document.querySelector("#divTwo"))
</script>
</body>
</html>