1. window.jQuery = function(selectorOrArrayOrTemplate){
    2. let elements
    3. if(typeof selectorOrArrayOrTemplate === 'string'){
    4. if(selectorOrArrayOrTemplate[0] === '<'){
    5. // 创建 div
    6. elements=[createElement(selectorOrArrayOrTemplate)]
    7. }else{
    8. // 查找 div
    9. elements = document.querySelectorAll(selectorOrArrayOrTemplate)
    10. }
    11. }else if(selectorOrArrayOrTemplate instanceof Array){
    12. elements = selectorOrArrayOrTemplate
    13. }
    14. function createElement(string){
    15. const container = document.createElement("template");
    16. container.innerHTML = string.trim();
    17. return container.content.firstChild;
    18. }
    19. // api 可以操作elements
    20. return {
    21. jquery: true,
    22. elements: elements,
    23. get(index){
    24. return elements[index]
    25. },
    26. appendTo(node){
    27. if(node instanceof Element){
    28. this.each(el => node.appendChild(el)) // 遍历 elements,对每个 el 进行 node.appendChild 操作
    29. }else if(node.jquery === true){
    30. this.each(el => node.get(0).appendChild(el)) // 遍历 elements,对每个 el 进行 node.get(0).appendChild(el)) 操作
    31. }
    32. },
    33. append(children){
    34. if(children instanceof Element){
    35. this.get(0).appendChild(children)
    36. }else if(children instanceof HTMLCollection){
    37. for(let i =0;i<children.length;i++){
    38. this.get(0).appendChild(children[i])
    39. }
    40. }else if(children.jquery === true){
    41. children.each(node => this.get(0).appendChild(node))
    42. }
    43. },
    44. find(selector){
    45. let array = []
    46. for(let i =0;i<elements.length;i++){
    47. const elements2 = Array.from(elements[i].querySelectorAll(selector))
    48. array = array.concat(elements2)
    49. }
    50. array.oldApi = this // this 就是 旧 api
    51. return jQuery(array)
    52. },
    53. each(fn){
    54. for(let i=0; i<elements.length;i++){
    55. fn.call(null, elements[i], i)
    56. }
    57. return this
    58. },
    59. parent(){
    60. const array = []
    61. this.each((node)=>{
    62. if(array.indexOf(node.parentNode) === -1){
    63. array.push(node.parentNode)
    64. }
    65. })
    66. return jQuery(array)
    67. },
    68. children(){
    69. const array = []
    70. this.each((node)=>{
    71. array.push(...node.children)
    72. })
    73. return jQuery(array)
    74. },
    75. print(){
    76. console.log(elements)
    77. },
    78. // 闭包:函数访问外部的变量
    79. addClass(className){
    80. for(let i=0;i<elements.length;i++){
    81. const element = elements[i]
    82. element.classList.add(className)
    83. }
    84. return this
    85. },
    86. oldApi: selectorOrArrayOrTemplate.oldApi,
    87. end(){
    88. return this.oldApi // this 就是新 api
    89. },
    90. }
    91. }
    92. window.$ = window.jQuery

    http://js.jirengu.com/qufec/1/edit?html,css,js,output