forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappend.html
More file actions
44 lines (37 loc) · 1.04 KB
/
append.html
File metadata and controls
44 lines (37 loc) · 1.04 KB
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript 模式和反模式</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* 题目: 附加
* 描述: 使用字符串连接和innerHTML的设定
*/
// 反模式
// 循环过程中附加
$.each(reallyLongArray, function (count, item) {
var newLI = '<li>' + item + '</li>';
$('#ballers').append(newLI);
});
// documentFragment off-DOM
// 用 documentFragment 可以起到 off-DOM 的作用, 在循环过程中,先附加在documentFragment 里,最后在一次放入DOM里:
var frag = document.createDocumentFragment();
$.each(reallyLongArray, function (count, item) {
var newLI = $('<li>' + item + '</li>');
frag.appendChild(newLI[0]);
});
$('#ballers')[0].appendChild(frag);
// 模式
// 循环过程中先使用字符串连接,之后再用innerHTML
var myhtml = '';
$.each(reallyLongArray, function (count, item) {
myhtml += '<li>' + item + '</li>';
});
$('#ballers').html(myhtml);
// 参考
// http://paulirish.com/2009/perf/
</script>
</body>
</html>