jq绑定事件

    <div style="100px;height:100px;border:1px solid red;overflow:auto;" id="box">
        <div style="50px;height:50px;border:1px solid red" id="content"></div>
    </div>
html元素

1、js绑定事件分为冒泡和捕获两种情况

2、冒泡执行顺序,先执行子元素的事件,再执行父元素的事件

3、捕获执行顺序,先执行父元素的事件,再执行子元素的事件

4、在既有捕获又有冒泡的情况下,先从外层一层一层往内执行捕获,一直到目标元素,目标元素按照绑定顺序执行。然后继续往外执行冒泡。这个是自己测试出来的结果,仅代表个人看法,和网上很多人的说法不一样。也欢迎大佬指正。

这里将流程划分为三部分:1、从外往内执行捕获。 2、达到目标元素后,按绑定顺序执行。3、从内往外冒泡

5、dom动画发生时,取到的dom数据是动画前的

6、停止事件的传播 e.stopPropagation();

在4的流程中,执行e.stopPropagation()可以让事件不传播的下一步骤,并且不传播的下一个dom节点。在第二步的同dom节点不受影响。

        
        $("#content").click(function (e) {
            //$(this).height(200); //第一次,直接改变高度
            $(this).animate({ "height": 200 }, 2000, function () {
                console.log("end");
            }).stop(true, true);//第二次,缓慢改变高度
            //e.preventDefault();
            console.log("content 冒泡1");
        });
        $("#content").click(function (e) {
            console.log('content 冒泡2', $(this).height());
        });
        $("#content").on("click", function () {
            console.log('content 冒泡3', $(this).height());
        });
        $("#content")[0].addEventListener("click", function (e) {
            console.log('content 捕获1', $(this).height());
        }, true);
        $("#content")[0].addEventListener("click", function () {
            console.log('content 捕获2', $(this).height());
        }, true);

        $("#box").click(function () {
            console.log('box 冒泡1', $("#content").height());
        });
        $("#box").on("click", function () {
            console.log('box 冒泡2', $("#content").height());
        });
        $("#box")[0].addEventListener("click", function (e) {
            console.log('box 捕获1', $("#content").height());
            e.stopPropagation();
        }, true);
        $("#box")[0].addEventListener("click", function (e) {
            console.log('box 捕获2', $("#content").height());
            //e.stopPropagation();
        }, true);


        $("#box").on("scroll", function () {
            console.log("resize");
        });
demo

 7、jquery on 绑定

jquery on 可以将子dom的事件绑到父节点上。执行顺序是 1、绑定在子节点的事件,2、绑定在父节点的子节点的事件 3、父节点的事件

        $("#box").on("click", function () {
            console.log('box 冒泡1', $(this).height());
        });
        $("#box").on("click","#content", function () {
            console.log('content 冒泡2', $("#content").height());
        });
        $("#content").on("click", function () {
            console.log('content 冒泡3', $(this).height());
        });
on 的顺序

 8、各种绑定冒泡事件的总结

8-1.选择器匹配到的元素比较多时,不要用bind() 或者 click(function(){})迭代绑定,会绑定很多事件

8-2.用delegate()或者on(),可以动态给子节点添加的绑定事件,绑定这个节点不能是动态的。

8-3.用delegate()和on()方法,dom树不要太深,因为一层一层冒泡上来影响性能。

9、自定义事件

        $("#box").click(function (e) {
            $("#box").trigger("clickCustom",["a","b"]);
        });

        $("#box").on("clickCustom",function () {
            console.log(arguments);
        });
demo
原文地址:https://www.cnblogs.com/tanl/p/5916455.html