1、Js表格,万条数据瞬间加载 在Ajax动态加载数据的实际应用中,大家都习惯了一种思维方式:一条数据创建一行。 于是如果数量大的时候,一次性要加载完数据的话,浏览器就会卡上半天 受Flex的DataGrid控件的启发,在Flex的DataGrid控件中,展示数据的方法并不是有多少条数据就创建多少行,它最多只创建你在界面上所看到的十几二十行(假设为n行),如果数据多的话,在滚动过程中,会从数据中抽取你应该看到的这n行数据,重新展示在已经创建好的那n行控件中。 也就是说,Flex的DataGrid控件中,我们实际上看到的仅仅是那n行控件,只是它们展示的数据是根据滚动条状态来筛选
2、出来的。 所以,如果在JS中,也用类似的方法实现,那么就是上万条数据,可能也只要创建几十个Dom而已,效率自然快得多了。 废话不多说,上代码。首先,需要一个滚动条 Scrollbar.js 复制代码 1. function Scrollbar() { 2. this.options = { 3. total : 0, //数据总数 4. pos : 0, //当前滚动位置 5. itemSize : 20, //单项尺寸 6. size : 200 //控件尺寸 7. }; 8. }
3、 9. Scrollbar.prototype = (function () { 10. function setOptions(options) { 11. for (var attr in options) { 12. this.options[attr] = options[attr]; 13. } 14. Refresh(this); 15. } 16. function Refresh(_this) { 17. if (!_this.created) 1
4、8. return; //设置控件高度 19. _this.bar.style.height = _this.options.size + "px"; 20. //设置内容高度 21. var ch = _this.options.total * _this.options.itemSize; 22. _this.content.style.height = ch + "px"; 23. } 24. //获取滚动位置 25. function getPos() { 2
5、6. var top = this.bar.scrollTop; 27. var pos = parseInt(top / this.options.itemSize); 28. return pos; 29. } 30. //每页可展示的数据数量 31. function getPageItems() { 32. return this.options.size / this.options.itemSize; 33. } 34. //滚动事件响应 35. fun
6、ction OnScroll(_this) { 36. var pos = _this.getPos(); 37. if (pos == _this.options.pos) 38. return; 39. _this.options.pos = pos; 40. _this.onScroll(pos); 41. } 42. //滚动条创建 43. function CreateAt(dom) { 44. var _this = this; 45.
7、 var bar = document.createElement("div"); 46. var content = document.createElement("div"); 47. bar.appendChild(content); 48. bar.style.width = "19px"; 49. bar.style.overflowY = "scroll"; 50. bar.style.overflowX = "hidden"; 51. if (bar.att
8、achEvent) { 52. bar.attachEvent("onscroll", function () { 53. OnScroll(_this); 54. }); 55. } else { 56. //firefox兼容 57. bar.addEventListener("scroll", function () { 58. OnScroll(_this); 59. },
9、 false); 60. } 61. content.style.backgroundColor = "white"; 62. content.style.width = "1px"; 63. this.bar = bar; 64. this.content = content; 65. if (typeof(dom) == "string") { 66. dom = document.getElementById(dom); 67. } 6
10、8. dom.innerHTML = ""; 69. dom.appendChild(this.bar); 70. this.created = true; 71. Refresh(this); 72. } 73. return { 74. setOptions : setOptions, 75. CreateAt : CreateAt, 76. getPos : getPos, 77. getPageItems : getPageI
11、tems, 78. onScroll : null 79. //模拟滚动条事件 80. }; 81. })(); 页面代码: 复制代码 1. 2. 3. 4.
5.12、
19、 57. 58.
59.|
66. ID
67. 20、 |
68. 69. Text 70. | 71.
|---|---|
| 77. | 78.79. | 80.






