[关闭]
@2890594972 2018-01-18T08:13:04.000000Z 字数 1447 阅读 689

封装jquery

封装jquery


在此输入正文

封装代码

  1. // 名字:jQuery 提供两个方法:静态,实例化方法
  2. // 使用闭包,封装jquery
  3. // $('#demo').css('backgroundColor','red');
  4. // jQuery('#demo').css('backgroundColor','red');
  5. var jQuery = (function(win){
  6. var win = win;
  7. function jQuery(selector){
  8. this.dom = [];
  9. if (typeof selector === 'object'){
  10. this.dom.push(selector);
  11. }else{
  12. // 改造
  13. var first = selector.charAt(0);
  14. switch (first) {
  15. case '#':
  16. this.dom[0] = document.getElementById(selector.slice(1));
  17. break;
  18. case '.':
  19. this.dom = document.getElementsByClassName(selector.slice(1));
  20. break;
  21. }
  22. }
  23. }
  24. // 原型方法
  25. jQuery.prototype.css = function(key, value){
  26. // this.dom.style[key] = value;
  27. var arr = this.dom;
  28. for (var i = 0; i < arr.length ; i++){
  29. arr[i].style[key] = value;
  30. }
  31. return this;
  32. }
  33. // 绑定事件
  34. jQuery.prototype.click = function(callback){
  35. var arr = this.dom;
  36. for(var i = 0; i< arr.length; i++){
  37. arr[i].onclick = (function(obj){ // 闭包
  38. return function(){
  39. // console.log(obj);
  40. callback.call(obj);
  41. }
  42. })(arr[i]);
  43. }
  44. }
  45. // 静态方法
  46. jQuery.each = function(){
  47. console.log(12345);
  48. }
  49. return jQuery;
  50. })(window);
  51. function $(selector){
  52. return new jQuery(selector);
  53. }
  54. $('#demo').css('background', 'red')
  55. .css('fontSize', '100px')
  56. .css('borderRadius', '20px')
  57. .css('color','#fff');
  58. $('.class-haha').css('background', 'red')
  59. .css('fontSize', '100px')
  60. .css('borderRadius', '20px')
  61. .css('color', '#fff');
  62. // $('#demo').css('fontSize','100px');
  63. // // jQuery('#demo').css('borderRadius','20px');
  64. // 使用方式
  65. $('.class-haha').click(function(){
  66. // console.log(111111111111111111,this);
  67. // this.style.backgroundColor = 'blue';
  68. // console.log(typeof this);
  69. $(this).css('backgroundColor','blue');
  70. })
  71. // jQuery.each();
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注