jQuery--事件处理

作者: 我可能是个假开发 | 来源:发表于2018-01-25 10:47 被阅读104次

    jQuery--事件处理

    一、事件模型

    1.浏览器事件模型
    ①DOM0级事件模型:只支持一个DOM事件处理函数
    • <input type="button" onclick="doSomething()"/>
    • input.onclick = function() { ... }
    • event = event || window.event;
    • var target = event.target || event.srcElement;
    • …

    代码示例:

    <body>
        <p id="example" onclick="console.log('Click');console.log('Click2');">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis praesentium, sapiente? Earum, molestiae rem. Enim, perspiciatis quisquam! A consequatur culpa error et, natus nobis placeat qui rem, suscipit tempora tenetur.
        </p>
        <div id="p1">
            <div id="p1-1">
                <div id="p1-1-1">
                    <div id="p1-1-1-1">
                        <p>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet architecto beatae delectus enim ipsum iusto laborum, libero minus perspiciatis quae quidem rem sed soluta velit veniam voluptatem voluptates voluptatibus. Repudiandae.
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <script>
        document.getElementById('example').onmouseover = function(event) {
            event = event || window.event;
            console.log('MouseOver: %o', event); //后面的事件会覆盖前面的
        };
        document.getElementById('example').onmouseover = function(event) {
            console.log('MouseOver2: %o', event);
        };
    
        document.getElementById('p1').onclick = function() {
            console.log('p1');
        };
        document.getElementById('p1-1').onclick = function() {
            console.log('p1-1');
        };
        document.getElementById('p1-1-1').onclick = function() {
            console.log('p1-1-1');
        };
        document.getElementById('p1-1-1-1').onclick = function(e) {
            console.log('p1-1-1-1');
            //        e.cancelBubble = true;//阻止事件冒泡
            e.stopPropagation();//阻止事件冒泡
        };
        </script>
    </body>
    

    ②DOM2级事件模型:事件不会覆盖

    • addEventListener(eventType, listener, useCapture)
      useCapture为false时跟DOM0级事件类似,只冒泡不捕获
      为true时:只捕获,不冒泡
    • attachEvent(eventName, handler)
    DOM事件模型.jpg

    代码示例:

    <body>
        <p id="example">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis praesentium, sapiente? Earum, molestiae rem. Enim, perspiciatis quisquam! A consequatur culpa error et, natus nobis placeat qui rem, suscipit tempora tenetur.
        </p>
        <div id="p1">
            <div id="p1-1">
                <div id="p1-1-1">
                    <div id="p1-1-1-1">
                        <p>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet architecto beatae delectus enim ipsum iusto laborum, libero minus perspiciatis quae quidem rem sed soluta velit veniam voluptatem voluptates voluptatibus. Repudiandae.
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <script>
        var element = document.getElementById('example');
        element.addEventListener('click', function(event) {
            console.log('Click1: %o', event);
        }, false);
        element.addEventListener('click', function(event) {
            console.log('Click2: %o', event);
        }, false);
        element.addEventListener('click', function(event) {
            console.log('Click3: %o', event);
        }, false);
    
        var useCapture = true;
    
        document.getElementById('p1').addEventListener('click', function() {
            console.log('p1');
        }, useCapture);
    
        document.getElementById('p1-1').addEventListener('click', function() {
            console.log('p1-1');
        }, useCapture);
    
        document.getElementById('p1-1-1').addEventListener('click', function() {
            console.log('p1-1-1');
        }, useCapture);
    
        document.getElementById('p1-1-1-1').addEventListener('click', function() {
            console.log('p1-1-1-1');
        }, useCapture);
        </script>
    </body>
    

    2.jQuery事件模型
    • 提供了统一的事件处理方法
    • 允许添加多个事件处理函数
    • 使用标准的事件名称(不带on)
    • 事件实例做为事件处理函数的第一个参数
    • 标准化事件实例最常用的属性
    • 提供了统一的事件取消和阻止默认行为的方法

    ①添加事件处理

    • on(eventType[, selector][, data], handler):在选择的元素上绑定一个或多个事件
      eventType:事件的名称(多个名称用空格分隔)
      [, selector]:选择器(事件委托时用到)
      [, data]:数据(传递一些数据给事件处理函数,从事件event的data属性中获取)
      handler:事件处理函数
    • bind()、delegate() 、live():过时

    ②统一方法和属性
    • 阻止冒泡: stopPropagation()
    • 阻止默认行为: preventDefault()
    • 阻止冒泡和默认行为:return false

    ③所有支持的事件
    • blur
    • change
    • click
    • dblclick
    • error
    • focus
    • focusin
    • focusout
    • keydown
    • keypress
    • keyup
    • load
    • unload
    • mousedown
    • mouseenter
    • mouseleave
    • mousemove
    • mouseout
    • mouseover
    • mouseup
    • ready
    • resize
    • scroll
    • select
    • submit

    ④一次性的事件处理:只执行一次
    • one(eventType[, selector][, data], handler)

    代码示例:

    <body>
        <h2>title</h2>
        <div class="item">
            <p>Lorem ipsum dolor sit amet.</p>
        </div>
        <ul>
            <li class="item1">新闻标题-1</li>
            <li class="item2">新闻标题-2</li>
            <li class="item3">新闻标题-3</li>
            <li class="item4">新闻标题-4</li>
            <li class="item5">新闻标题-5</li>
            <li class="item6">新闻标题-6</li>
            <li class="item7">新闻标题-7</li>
            <li class="item8">新闻标题-8</li>
            <li class="item9">新闻标题-9</li>
        </ul>
        <div id="p1">
            <div id="p1-1">
                <div id="p1-1-1">
                    <div id="p1-1-1-1">
                        <p>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet architecto beatae delectus enim ipsum iusto laborum, libero minus perspiciatis quae quidem rem sed soluta velit veniam voluptatem voluptates voluptatibus. Repudiandae.
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
    
            //        $('p')
            //            .on('click', null, null, function (e) {
            //                console.log('p clicked'); //所有的p都绑定了
            //            })
            //            .on('click', function (e) {
            //                console.log('p clicked2');
            //            })
            //            .on('click', { foo: 'bar' }, function (e) {
            //                console.log('p clicked3 %o', e.data);//%o 在控制台把对象显示出来
            //            })
            //            .on('mouseover', function (e) {
            //                console.log('p mouseover');
            //            })
            //            .on('mouseover', function (e) {
            //                console.log('p mouseover2');
            //            })
            //            .on('click mouseover', function (e) {
            //                console.log('p click or mouseover');
            //            })
    
            //        $('ul').on('click', 'li.item2', function () {
            //            console.log('li clicked');
            //        })
    
            //        $('li').on('click', function (e) {
            //            console.log('Clicked: %o', $(this));
            //        })
    
            //        $('ul').on('click', 'li', function (e) {
            //            console.log('Clicked: %o', $(e.target));
            //        })
    
            //        $('div').on('click', function () {
            //            console.log(this.id);
            //        })
            //        $('p').on('click', function (e) {
            //            e.stopPropagation()
            //            console.log('clicked p');
            //        })
    
            //        $('p').on({
            //            click: function () {
            //                console.log('click');
            //            },
            //            mouseover: function () {
            //                console.log('mouseover');
            //            }
            //        })
    
            $('p').one('click', function(e) {
                console.log('clicked p');
            });
        });
        </script>
    </body>
    

    ⑤移除事件处理
    • off(eventType[, selector][, handler])
    • off()

    <body>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur assumenda debitis fugiat laboriosam magni modi sequi, sint ullam! Ad consequatur cum excepturi modi nam quos. Dolor est laudantium minima ratione.</p>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
    
            var clicked2 = function(e) {
                console.log('clicked2');
            };
    
            $('p').on('click', function(e) {
                console.log('clicked');
            }).on('click', clicked2).on('mouseover', function(e) {
                console.log('mouseover');
            });
    
            //        $('p').off('click') //不带参数 移除所有事件处理
            //        $('p').off('mouseover')
            //        $('p').off('click mouseover')//移除多个
            //        $('p').off('click', clicked2)//移除特定的clicked2
        });
        </script>
    </body>
    

    二、事件实例对象

    1.事件实例对象的属性
    altKey
    bubbles
    button
    cancelable
    charCode
    clientX
    clientY
    ctrlKey
    currentTarget
    data
    detail
    delegateTarget
    eventPhase
    metaKey
    namespace
    offsetX
    offsetY
    originalTarget
    originalEvent
    pageX
    pageY
    prevValue
    relatedTarget
    result
    screenX
    screenY
    shiftKey
    target
    timeStamp
    type
    view
    which

    2.事件实例对象的方法
    • preventDefault():阻止浏览器默认事件
    • stopPropagation():阻止冒泡
    • stopImmediatePropagation():立刻阻止事件处理函数并防止事件冒泡(阻止冒泡还阻止后续绑定的)
    • isDefaultPrevented():对以上三个方法是否调用的一个检测,调用了就返回true
    • isPropagationStopped()
    • isImmediatePropagationStopped()

    代码示例:

    <body>
        <div id="p1">
            <div id="p1-1">
                <div id="p1-1-1">
                    <div id="p1-1-1-1">
                        <p>
                            Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet architecto beatae delectus enim ipsum iusto laborum, libero minus perspiciatis quae quidem rem sed soluta velit veniam voluptatem voluptates voluptatibus. Repudiandae.
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
            $('div').on('click', function(e) {
                console.log('clicked: %o', $(this));
            });
            $('p').on('click', function(e) {
                e.stopPropagation();
                console.log('clicked1: p');
                console.log(e.isPropagationStopped());
            });
            $('p').on('click', function(e) {
                console.log('clicked2: p');
            });
        });
        </script>
    </body>
    

    3.触发事件
    • trigger(eventType[, data]):主动触发事件
    • triggerHandler(eventType[, data])

    区别
    triggerHandler 相比 trigger:
    • 不会触发浏览器默认事件;
    • 不会产生事件冒泡;
    • 只触发jQuery对象集合中第一个元素的事件处理函数;
    • 返回的是事件处理函数的返回值,而不是jQuery对象。(所以不能使用链式语法)

    代码示例:

    <body>
        <ul>
            <li class="item1">新闻标题-1</li>
            <li class="item2">新闻标题-2</li>
            <li class="item3">新闻标题-3</li>
            <li class="item4">新闻标题-4</li>
            <li class="item5">新闻标题-5</li>
            <li class="item6">新闻标题-6</li>
            <li class="item7">新闻标题-7</li>
            <li class="item8">新闻标题-8</li>
            <li class="item9">新闻标题-9</li>
        </ul>
        <button id="all">全部标记为已读</button>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
            $('li').on('click', function(e, arg1, arg2) {
                console.log('%o 已读', $(this));
                console.log(arg1);
                console.log(arg2);
                return $(this);
            });
    
            $('#all').on('click', function() {
                console.log($('li').trigger('click', [1, 2]));
                console.log($('li').triggerHandler('click'));
            });
        });
        </script>
    </body>
    

    4.快捷方法
    blur
    change
    click
    dblclick
    focus
    focusin
    focusout
    keydown
    keypress
    keyup
    mousedown
    mouseenter
    mouseleave
    mousemove
    mouseout
    mouseover
    mouseup
    ready
    resize
    scroll
    select
    submit

    快捷方法的使用
    • eventName([data,] handler)
    • eventName()

    代码示例:

    <body>
        <ul>
            <li class="item1">新闻标题-1</li>
            <li class="item2">新闻标题-2</li>
            <li class="item3">新闻标题-3</li>
            <li class="item4">新闻标题-4</li>
            <li class="item5">新闻标题-5</li>
            <li class="item6">新闻标题-6</li>
            <li class="item7">新闻标题-7</li>
            <li class="item8">新闻标题-8</li>
            <li class="item9">新闻标题-9</li>
        </ul>
        <button id="all">全部标记为已读</button>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
            $('li').click(function(e) {
                console.log('%o 已读', $(this));
            });
            //        $('li').dblclick(function (e) {
            //            console.log('%o 又读', $(this));
            //        })
    
    
            $('#all').on('click', function() {
                console.log($('li').click());
            });
        });
        </script>
    </body>
    

    5.hover方法
    • hover(enterHandler, leaveHandler)
    • hover(handler)

    代码示例:

    <head>
        <meta charset="UTF-8">
        <title>demo</title>
        <style>
        .outer {
            width: 200px;
            height: 200px;
            padding: 20px;
            color: #fff;
            background-color: green;
        }
        
        .inner {
            width: 100px;
            height: 100px;
            margin: 30px auto;
            padding: 20px;
            color: #fff;
            background-color: orange;
        }
        
        #outer2 {
            margin-top: 50px;
        }
        </style>
    </head>
    
    <body>
        <div class="outer" id="outer1">
            Outer 1
            <div class="inner" id="inner1">Inner 1</div>
        </div>
        <div class="outer" id="outer2">
            Outer 2
            <div class="inner" id="inner2">Inner 2</div>
        </div>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
            function report(event) {
                event.stopPropagation();
                console.log(event.type + ' on ' + event.target.id);
            }
    
            $('#outer1').on('mouseover mouseout', report);
            $('#inner1').on('mouseover mouseout', report);
            $('#outer2').hover(report);
            $('#inner2').hover(report);
        });
        </script>
    </body>
    

    6.自定义事件
    • on(customEvent)
    • trigger(customEvent)

    <body>
        <ul>
            <li class="item1">新闻标题-1</li>
            <li class="item2">新闻标题-2</li>
            <li class="item3">新闻标题-3</li>
            <li class="item4">新闻标题-4</li>
            <li class="item5">新闻标题-5</li>
            <li class="item6">新闻标题-6</li>
            <li class="item7">新闻标题-7</li>
            <li class="item8">新闻标题-8</li>
            <li class="item9">新闻标题-9</li>
        </ul>
        <button id="all">全部标记为已读</button>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
    
            $('li').on('markAsRead', function(e) {
                console.log('%o 已读', $(this));
            });
    
            $('li').on('click', function(e) {
                $(this).trigger('markAsRead');
            });
    
            $('#all').on('click', function() {
                $('li').trigger('markAsRead');
            });
        });
        </script>
    </body>
    

    7.事件命名空间
    • eventName.namespace

    <body>
        <ul>
            <li class="item1">新闻标题-1</li>
            <li class="item2">新闻标题-2</li>
            <li class="item3">新闻标题-3</li>
            <li class="item4">新闻标题-4</li>
            <li class="item5">新闻标题-5</li>
            <li class="item6">新闻标题-6</li>
            <li class="item7">新闻标题-7</li>
            <li class="item8">新闻标题-8</li>
            <li class="item9">新闻标题-9</li>
        </ul>
        <button id="even">点击偶数</button>
        <button id="odd">点击奇数</button>
        <button id="all">全部点击</button>
        <script src="../../../vendor/jquery-1.12.4.js"></script>
        <script>
        $(function() {
    
            $('li:odd').on('click.even', function(e) {
                console.log('%o 偶数', $(this));
            });
    
            $('li').eq(0).on('click.even.0', function(e) {
                console.log('%o 0', $(this));
            });
    
            $('li:even').on('click.odd', function(e) {
                console.log('%o 奇数', $(this));
            });
    
            $('#even').on('click', function() {
                $('li').trigger('click.even');
            });
    
            $('#odd').on('click', function() {
                $('li').trigger('click.odd');
            });
    
            $('#all').on('click', function() {
                //            $('li').trigger('click');
                $('li').trigger('click.even.0');
            });
    
            //        $('li').off('.even') 
        });
        </script>
    </body>

    相关文章

      网友评论

        本文标题:jQuery--事件处理

        本文链接:https://www.haomeiwen.com/subject/bdomaxtx.html