码迷,mamicode.com
首页 > 其他好文 > 详细

事件委托

时间:2018-06-07 17:46:40      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:ems   ext   cti   .text   jquery   nts   events   asp   highlight   

事件委托就是利用事件冒泡原理,把处理任务委托给父元素或者祖先元素(通常用父元素),我们通过目标对象来判断事件源,并执行事件处理。

jQuery实现事件委托可以调用on()方法,这样写:

1
$(el).on( events [, selector ] [, data ], handler(eventObject) )

el是父元素,selector是子元素,事件处理函数。

示例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>事件委托</title>
        </script>
    </head>
    <body>
        <div>
            <ul id="ul">
                <li id="a">鼠标</li>
                <li id="b">键盘</li>
                <li id="c">屏幕</li>
                <li id="d"><a>主机</a></li>
            </ul>
        </div>
        <p id="notes">单击列表项,或光标移到列表项</p>
        <script>
            $(‘ul‘).on(‘click mouseover‘,‘:not(#four)‘,
                    function (e) {
                        listItem = ‘列表项 ‘ + e.target.textContent + ‘<br />‘;
                        eventType = ‘事件  ‘ + e.type;
                        $(‘#notes‘).html(listItem +  eventType);
                    });
        </script>
    </body>
</html>

示例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>事件委托</title>
        </script>
    </head>
    <body>
        <div>
            <ul id="ul">
                <li id="a">鼠标</li>
                <li id="b">键盘</li>
                <li id="c">屏幕</li>
                <li id="d"><a>主机</a></li>
            </ul>
        </div>
        <p id="notes">单击列表项,或光标移到列表项</p>
        <script>
            $(‘ul‘).on(‘click mouseover‘, ‘:not(#four)‘,
                    {status: ‘important‘},
                    function (e) {
                        listItem = ‘列表项 ‘ + e.target.textContent + ‘<br />‘;
                        itemStatus = ‘状态 ‘ + e.data.status + ‘<br />‘;
                        eventType = ‘事件  ‘ + e.type;
                        $(‘#notes‘).html(listItem + itemStatus + eventType);
                    });
        </script>
    </body>
</html>

事件委托

标签:ems   ext   cti   .text   jquery   nts   events   asp   highlight   

原文地址:https://www.cnblogs.com/max-hou/p/9151722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!