zoukankan      html  css  js  c++  java
  • 5.jQuery实现简单的on()和trigger()方法

    # jQuery事件

    - 1.on()
    ```js
    //1.事件类型type 2.selector 3.data 4.handle
    $('ul').on('click', 'li', function(e){
        alert($(e.target).text());
    });//点击ul下的li元素触发handle事件

    $('.demo').on({
        click:function(){
            console.log("click");
        },
        mouseenter:function(){
            console.log("mouseenter");
        },
        mouseleave:function(){
            console.log("mouseleave");
        }
    });//为.demo元素绑定多个事件
    ```

    - 2.one() 事件只触发一次
    ```js
    //1.事件类型type 2.selector 3.data 4.handle
    $('ul').one('click', function(e){
        alert($(e.target).text());
    });//点击ul下的li元素触发handle事件
    ```

    - 3.off() 解绑事件
    ```js
    $('.demo').off('click', clickTwo);//解绑点击事件clickTwo;
    //最好前面怎样绑定事件,后面怎样解绑事件,参数一致
    ```

    - 4.trigger() 主动触发事件(系统事件和自定义事件)
    ```js
    $('.demo').on('click', function(e, a, b, c, d){
        console.log('click', a, b, c, d);
    });
    $('.demo').trigger('click', [10, 20, 30, 40]);//触发事件的时候可以传递参数
    ```

    - 5.hover()
    ```js
    $('demo').hover(function(){
        console.log('hoverEnter');
    },function(){
        console.log('hoverLeave');
    });
    //等价于同时绑定mouseenter和mouseleave事件
    $('.demo').on('mouseenter', function(){
        console.log('enter');
    }).on('mouseleave', function(){
        console.log('leave');
    });
    ```
     
    以上是markdown格式的笔记
     
    实现简单的on()和trigger()函数:
    (function () {
        //创建一个jQuery构造函数
        function jQuery(selector) {
            return new jQuery.prototype.init(selector);
        }
        //为jQuery的原型添加init属性,所有实例可以使用该属性
        jQuery.prototype.init = function (selector) {
            this.length = 0; //为this添加length属性,并且赋值为0
            //选出 dom 并且包装成jQuery对象返回
            //判断selector是null 和 undefined 和 dom对象 和 id 和 class的情况
            if (selector == null) { //判断selector是null或undefined
                return this;
            } else if (typeof selector === 'string' && selector.indexOf('.') != -1) { //selector是class的情况
                var dom = document.getElementsByClassName(selector.slice(1));
            } else if (typeof selector === 'string' && selector.indexOf("#") != -1) { //selector是id的情况
                var dom = document.getElementById(selector.slice(1));
            }
    
            if (selector instanceof Element || dom.length == undefined) { //(selector是dom对象) || (selector是id,返回的是一个对象,对象没有length属性)
                this[0] = dom || selector; //(selector是id) || (selector是dom对象)
                this.length++;
            } else { //selector是class,返回的是一个类数组
                for (var i = 0; i < dom.length; i++) {
                    this[i] = dom[i];
                    this.length++;
                }
            }
        };
    
        //为jQuery的原型添加css属性,所有实例可以使用该属性
        jQuery.prototype.css = function (config) {
            for (var i = 0; i < this.length; i++) {
                for (var prop in config) {
                    this[i].style[prop] = config[prop];
                }
            }
    
            return this; //链式调用的精髓
        };
    
        //为jQuery对象的prevObject属性赋值,从而可以使用end()方法
        jQuery.prototype.pushStack = function (dom) {
            //dom是jQuery对象
            if (dom.constructor != jQuery) { //dom是原生的dom对象
                dom = jQuery(dom); //将原生dom对象包裹成jQuery对象
            }
            dom.prevObject = this; //
    
            return dom;
        };
    
        //为jQuery的原型添加get属性,所有实例可以使用该属性
        jQuery.prototype.get = function (num) {
            //num == null 返回数组
            //num >= 0 返回this[num]
            //num < 0 返回this[length + num]
            return (num != null) ? ((num >= 0) ? (this[num]) : (this[num + this.length])) : ([].slice(this, 0));
        };
    
        //为jQuery的原型添加get属性,所有实例可以使用该属性
        jQuery.prototype.eq = function (num) {
            return this.pushStack(this.get(num)); //调用jQuery.prototype.get()函数获取到dom对象,再封装为jQuery对象并且为jQuery对象添加prevObject属性
        };
    
        //为jQuery的原型添加add属性,所有实例可以使用该属性
        jQuery.prototype.add = function (selector) {
            var curObj = jQuery(selector); //当前通过add添加的selector选中的jQuery对象
            var prevObj = this; //调用add()的jQuery对象
            var newObj = jQuery();
    
            for (var i = 0; i < curObj.length; i++) {
                newObj[newObj.length++] = curObj[i];
            }
    
            for (var i = 0; i < prevObj.length; i++) {
                newObj[newObj.length++] = prevObj[i];
            }
    
            this.pushStack(newObj); //为jQuery对象添加prevObject属性
    
            return newObj; //将合并后的jQuery对象返回
        };
    
        //为jQuery的原型添加end属性,所有实例可以使用该属性
        jQuery.prototype.end = function () {
            return this.prevObject; //直接返回前一个jQuery对象
        };
    
        //为jQuery的原型添加on属性,所有实例可以使用该属性
        jQuery.prototype.on = function (type, handle) {
            for (var i = 0; i < this.length; i++) {
                if (!this[i].cacheEvent) {//判断每一个原生dom对象中是否有事件
                    this[i].cacheEvent = {}; //为每一个原生的dom对象添加绑定事件
                }
                if (!this[i].cacheEvent[type]) {//判断每一个原生对象是否有type类型的绑定事件
                    this[i].cacheEvent[type] = [handle];//没有则为该类型事件添加处理函数数组
                } else {
                    this[i].cacheEvent[type].push(handle);//若已经有该类型事件,则直接放入数组
                }
            }
        };
    
        //为jQuery的原型添加trigger属性,所有实例可以使用该属性
        jQuery.prototype.trigger = function (type) {
            var self = this;//将调用trigger函数的jQuery对象存放在self中
            var params = arguments.length > 1 ? [].slice.call(arguments, 1) : [];//判断调用trigger()函数时是否传入除了type以外的其他参数
            for (var i = 0; i < this.length; i++) {//循环遍历this
                if (this[i].cacheEvent[type]) {//判断每个原生dom对象中是否存放有type类型的事件
                    this[i].cacheEvent[type].forEach(function (ele, index) {//有多个相同类型的事件时,要全部依次执行
                        ele.apply(self, params);//通过self调用事件,并且把参数传入
                    });
                }
            }
        };
    
        //上面的jQuery构造函数是new 一个jQuery.prototype.init对象,
        //jQuery.prototype.init对象上没有jQuery.prototype上的css()方法
        //所以添加下面一句,让jQuery.prototype.init对象可以调用jQuery.prototype上的css()方法
        jQuery.prototype.init.prototype = jQuery.prototype;
    
        //让外部可以通过$()或者jQuery()调用
        window.$ = window.jQuery = jQuery;
    }());
    myJquery.js
    调用on()和trigger()函数:
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .demo {
                width: 100px;
                height: 100px;
                background: yellow;
            }
        </style>
    </head>
    
    <body>
        <div class="demo"></div>
        <script src="./myJquery.js"></script>
        <script>
            $('.demo').on('click', function (a, b, c) {
                console.log("click1" + a + b + c);
            });
            $('.demo').on('click', function (a) {
                console.log("click2" + a);
            });
            $('.demo').trigger('click', 1, 2, 3);
        </script>
    </body>
    
    </html>
    index.html

    效果展示:

  • 相关阅读:
    file_put_contents实现内容追加
    Laravel5.5 实现session配置
    easywechat在laravel框架中的应用-代码参考
    Laravel框架模型层表单验证
    工厂方法模式及php实现
    简单工厂模式及php实现
    Actionscript,AS3,MXML,Flex,Flex Builder,Flash Builder,Flash,AIR,Flash Player之关系
    php之依赖注入和控制反转
    php pdo操作数据库
    odbc连接数据库
  • 原文地址:https://www.cnblogs.com/lanshanxiao/p/12867895.html
Copyright © 2011-2022 走看看