delegate === on

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            * {
                background: rgba(0,0,0,.1);
            }
        </style>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    </head>
    <body>
        <p>1</p>
        <script type="text/javascript">
            $(function(){
                $('body').delegate('p','click',function(e){
                    $(this).after("<p>Hello world!</p>");
                })
            });
        </script>
    </body>
</html>

  • delegateon 利用事件冒泡对元素进行事件绑定,比bind对指定的所有元素进行绑定更加高效

  • 使用 on吧 , 能完成所有其它的事件绑定方法,但它更短更简洁,其它的绑定方法都是由它实现的

For example, the following .delegate() code:

$("table").delegate("td", "click", function() {
$(this).toggleClass("chosen"); });

is equivalent to the following code written using .on():

$("table").on("click", "td", function() {
$(this).toggleClass("chosen"); });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。