-
Notifications
You must be signed in to change notification settings - Fork 4
/
jQuery之html().html
107 lines (96 loc) · 3.5 KB
/
jQuery之html().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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery之html()</title>
</head>
<body>
<script src="jQuery.js"></script>
<div class="divOne">
<p>嘿嘿嘿</p>
</div>
<div class="divOne">
<p>嘿嘿嘿</p>
</div>
<input type="text" id="inputOne">
<script>
function customHtml(value) {
//默认是选取第一个目标元素
let elem = this[0] || {},
i = 0,
l = this.length;
//如果是html(),即使读取目标元素的innerHTML的话
if (value === undefined && elem.nodeType === 1) {
return elem.innerHTML;
}
//根据目标元素的个数,依次对符合条件的目标元素赋值
for (; i < l; i++) {
elem = this[i] || {};
if (elem.nodeType === 1) {
elem.innerHTML = value;
}
}
}
// html()方法设置或返回被选元素的内容(innerHTML)
// 当该方法用于返回内容时,则返回第一个匹配元素的内容
// 当该方法用于设置内容时,则重写所有匹配元素的内容
// http://www.runoob.com/jquery/html-html.html
// 源码6203行左右
function html( value ) {
//调用$().html()方法,即调用access()方法
//关于access()方法的讲解,请看:https://www.cnblogs.com/gongshunkai/p/5905917.html
//access(this,function(),null,value,arguments.length)
return jQuery.access( this, function( value ) {
//读的话(.html())只读第一个匹配的目标元素的内容所以是this[0]
//写的话(.html(xxx))会循环每个匹配的目标并将其innerHTML置为value
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
//当直接调用html(),并且目标元素是元素节点时,$().html()的本质是 selector.innerHTML
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
//如果能直接使用innerHTML来解析的话
//注意:IE的innerHTML会忽略开头的无作用域元素
if ( typeof value === "string" &&
!rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
//Hello <b>world</b>!
value = jQuery.htmlPrefilter( value );
console.log(value,'value6235')
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
console.log(3333,'node6261')
// getAll( elem, false ):获取原本selector内部的内容(标签)
//先移除元素节点和注册的事件以防止内存泄漏
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
//将elem置为0,是防止执行下面的if(elem)...
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
}
customHtml.call(document.querySelectorAll(".divOne"))
customHtml.call(document.querySelectorAll(".divOne"),"Hello <b>world</b>!")
// console.log($(".divOne").html())
// $(".divOne").html("Hello <b>world</b>!")
// let p=document.createElement('p')
// p.innerText='哈哈哈gggg'
// $(".divOne").html(p)
// console.log(p,'p19')
// $("#divOne").text('<p>aaaa</p>')
// $("#divOne").text(p)
</script>
</body>
</html>