当前位置: 移动技术网 > IT编程>开发语言>Jquery > 5.jQuery实现简单的on()和trigger()方法

5.jQuery实现简单的on()和trigger()方法

2020年05月11日  | 移动技术网IT编程  | 我要评论

国际清廉指数,棵的组词,李鸾英

# 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;
}());
调用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>

效果展示:

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网