zoukankan      html  css  js  c++  java
  • [DOM Event Learning] Section 3 jQuery事件处理基础 on(), off()和one()方法使用

    [DOM Event Learning] Section 3 jQuery事件处理基础 on(),off()和one()方法使用

     
      jQuery提供了简单的方法来向选择器(对应页面上的元素)绑定事件处理器(event handlers).
      当一个事件发生,提供的function就被执行,在方法里面,this代表当前的元素.
      这些事件通常是由于用户和页面的交互而被激发,比如文字输入到表单元素,鼠标指针移动等.也有一些情况,比如页面load和unload的事件,是由浏览器本身来激发.
      关于Events的细节,可以查看:http://api.jquery.com/category/events/
      事件处理方法可以接收一个event对象,这个对象被用来判定事件类型,或者制止默认行为等.
      event对象的详细介绍可以参见:http://api.jquery.com/category/events/event-object/
     

    jQuery的事件绑定方法

      jQuery为绝大多数浏览器事件提供了方便的方法,比如.click(), .focus(), .blur(), .change()等,它们都是.on()方法的简便形式.
      比如下面两个方法的效果是一样的:
    复制代码
    // Event setup using a convenience method
    $("p").click(function () {
        console.log("You clicked a paragraph!");
    });
    // Equivalent event setup using the `.on()` method
    $("p").on("click", function () {
        console.log("click");
    });
    复制代码
     

    .on()方法

      .on()方法使用起来很灵活,在很多场合很有用,比如为多个事件绑定同一个处理方法,当你想给处理方法传数据,或者处理自定义事件,或当你想要传递多个事件和方法时.
     
      为多个事件绑定同一个处理方法时,用空格分隔事件名:
    复制代码
    // Multiple events, same handler
    $("input").on(
        "click change", // Bind handlers for multiple events
        function () {
            console.log("An input was clicked or changed!");
        }
    );
    复制代码
      如果多个事件的处理方法不同,也可以一次绑定,因为.on()方法可以接收传入一个大括号包含的PlainObject对象,其中是一个或多个key value,key是事件名,value是处理函数.
    复制代码
    // Binding multiple events with different handlers
    $("p").on({
        "click": function () {
            console.log("clicked!");
        },
        "mouseover": function () {
            console.log("hovered!");
        }
    });
    复制代码
      但是需要注意的是.on()方法只能对当前存在的元素绑定事件.
      如果在.on()方法执行之后,新建了一个符合选择器的元素,这个新建的元素并不会执行这个前面绑定的事件处理方法.
    复制代码
    $(document).ready(function () {
    
        // Sets up click behavior on all button elements with the alert class
        // that exist in the DOM when the instruction was executed
        $("button.alert").on("click", function () {
            console.log("A button with the alert class was clicked!");
        });
    
        // Now create a new button element with the alert class. This button
        // was created after the click listeners were applied above, so it
        // will not have the same click behavior as its peers
        $("<button class='alert'>Alert!</button>").appendTo(document.body);
    });
    复制代码

    事件对象

      每一个事件处理函数都接收一个事件对象(Event Object),这个对象包含很多属性和方法.
      一个很常用的方法是用.preventDefault()来阻止事件的默认行为.
      其他有用的属性和方法包括:
      pageX, pageY: 事件发生时的鼠标指针位置.相对于页面显示区域的左上角,而不是浏览器窗口.
      type: 事件类型,比如”click”.
      which: 被点击的button或key.
      data: 事件被绑定的时候传入的数据.比如:
    复制代码
    // Event setup using the `.on()` method with data
    $("input").on(
        "change",
        {foo: "bar"}, // Associate data with event binding
        function (eventObject) {
            console.log("An input value has changed! ", eventObject.data.foo);
        }
    );
    复制代码
      target: 初始化这个事件的DOM元素,也即分发这个事件的元素.
      namespace: 这个事件激发时指定的namespace.
      timeStamp: 事件发生时距离1970年1月1日的时间戳,单位是milliseconds.
     
      preventDefault(): 阻止事件的默认行为.
      stopPropagation(): 阻止事件向上冒泡到其他元素.
      这两个方法一起用的时候,可以用return false来代替,更加简洁.
     
      originalEvent属性是浏览器自己创造的一个event对象,jQuery又包装了一下这个对象,有一些有用的方法和属性,这些在处理移动设备的touch events的时候很有用.
     
      除了事件对象之外,事件处理函数还可以通过this关键字访问该事件绑定的DOM元素,我们可以把这个DOM元素转换为jQuery对象:
    var $element = $(this);

    解除事件监听器

      要解除event listener,可以使用.off()方法,传入要解除绑定的事件类型.
      如果你附加了一个有名字的function,那么你可以通过第二个参数,指定仅解除这个名字的事件处理函数.
    复制代码
    // Tearing down all click handlers on a selection
    $("p").off("click");
    
    // Tearing down a particular click handler, using a reference to the function
    var foo = function () {
        console.log("foo");
    };
    var bar = function () {
        console.log("bar");
    };
    
    $("p").on("click", foo).on("click", bar);
    $("p").off("click", bar); // foo is still bound to the click event
    复制代码
     
     

    设置只执行一次的事件处理

      有时候你需要一个handler只执行一次,或者你想执行一次之后换一个handler, jQuery为这种情况提供了.one()方法.
    复制代码
    // Switching handlers using the `.one()` method
    $("p").one("click", firstClick);
    
    function firstClick() {
        console.log("You just clicked this for the first time!");
    
        // Now set up the new handler for subsequent clicks;
        // omit this step if no further click responses are needed
        $(this).click(function () {
            console.log("You have clicked this before!");
        });
    }
    复制代码
      注意上面这段代码中,这个firstClick方法将在所有p元素第一次被点击的时候执行一次,而不是某个p被点击一次之后就从所有p中移除该方法.
     
      .one()方法也可以用来绑定多个事件:
    复制代码
    // Using .one() to bind several events
    $("input[id]").one("focus mouseover keydown", firstEvent);
    
    function firstEvent(eventObject) {
        console.log("A " + eventObject.type + " event occurred for the first time on the input with id " + this.id);
    }
    复制代码
      这种情况下,所有事件的第一次执行都会进入这个处理方法.
      对这段代码来说,也即,即便input已经获得了焦点,但是第一次keydown事件的时候还是会执行这个方法.
     
     

    参考资料

      jQuery Events: http://learn.jquery.com/events/
      jQuery API Events: http://api.jquery.com/category/events/
     
      w3school jQuery参考手册 事件: http://www.w3school.com.cn/jquery/jquery_ref_events.asp
      JavaScript事件参考手册: http://www.w3school.com.cn/jsref/jsref_events.asp
  • 相关阅读:
    Mayan游戏 (codevs 1136)题解
    虫食算 (codevs 1064)题解
    靶形数独 (codevs 1174)题解
    黑白棋游戏 (codevs 2743)题解
    神经网络 (codevs 1088) 题解
    The Rotation Game (POJ 2286) 题解
    倒水问题 (codevs 1226) 题解
    银河英雄传说 (codevs 1540) 题解
    生日蛋糕 (codevs 1710) 题解
    第一章 1.11 高阶函数
  • 原文地址:https://www.cnblogs.com/Alex80/p/5101670.html
Copyright © 2011-2022 走看看