• 事件绑定的快捷方式 利on进行事件绑定的几种情况


    【事件绑定快捷方式】
    $("button:first").click(function(){
    alert(1);
    });

    【使用on绑定事件】


     ① 使用on进行单事件绑定
     $("button").on("click",function(){
     //$(this) 取到当前调用事件函数的对象
    console.log($(this).html());
    });

     ② 使用on同时为多个事件,绑定同一函数
    $("button").on("mouseover click",function(){
    console.log($(this).html())
    })

      ③ 调用函数时,传入自定义参数
    $("button").on("click",{name:"jianghao"},function(event){
    // 使用event.data.属性名 找到传入的参数
    console.log(event.data.name);
    })*/

    ④ 使用on进行多事件多函数绑定
    $("button").on({
    click:function(){
    console.log("click")
    },
    mouseover:function(){
    console.log("mouseOver")
    }
    });

     ⑤ 使用on进行事件委派
     >>> 将原本需要绑定到某元素上的事件,改为绑定在父元素乃至根节点上,然后委派给当前元素生效;
     eg:$("p").click(function(){});

                         ↓          

     $(document).on("click","p",function(){});
     >>> 作用:
     默认的绑定方式,只能绑定到页面初始时已有的p元素,当页面新增p元素时,无法绑定到新元素上;
     使用事件委派方式,当页面新增元素时,可以为所有新元素绑定事件



    $("button").on("click",function(){
    var p = $("<p>444444</p>");
    $("p").after(p);
    });

    $("p").click(function(){
    alert(1);
    });

    $(document).on("click","p",function(){
    alert(1);
    });




     off() 取消事件绑定

    1. $("p").off(): 取消所有事件
    2. $("p").off("click"): 取消点击事件
    3. $("p").off("click mouseover"):取消多个事件
    4. $(document).off("click","p"):取消事件委派





     使用.one() 绑定事件,只能执行一次

    $("button").one("click",function(){
    alert(1);
    })



    /* .trigger("event"):自动触发某元素的事件
    *
    * $("p").trigger("click",["haha","hehe"]); 触发事件时,传递参数
    */
    /*$("p").click(function(event,arg1,arg2){
    alert("触发了P的click事件"+arg1+arg2);
    })

    $("button").click(function(){
    $("p").trigger("click",["haha","hehe"]);
    })*/

  • 相关阅读:
    python_day_5:20180720
    python_day_4:20180719
    2018悦读
    2018生活
    心理画
    js 策略模式
    js 单例模式
    js 模板方法模式
    C语言-数据类型
    js 观察者模式
  • 原文地址:https://www.cnblogs.com/GlenLi/p/6754116.html
Copyright © 2020-2023  润新知