Why do you have to pass the event object as a parameter?

后端 未结 5 1435
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 10:37

I\'m learning how to manipulate events in JavaScript and I\'m wondering \"why do you have to pass the event object as a parameter (argument) into a function when using event

5条回答
  •  礼貌的吻别
    2020-12-28 11:01

    The Ever-Present Event, Whether You Like it or Not

    The event is always present, even when you don't provide a name:

    $(".foo").on("click", function(){
      alert( arguments[0].type );
    });
    

    That is the same as saying this:

    $(".foo").on("click", function(event){
      alert( event.type );
    });
    

    The event object is already being passed to your callback (whether your provide a name for it or not), you can choose to not use it if you like. For instance, if we looked to a jQuery onClick method:

    $(".foo").on("click", function(){
      /* Do stuff */
    });
    

    Making Use of It

    You'll note that I have no event object referenced in my callback. I'm not required to. However, if I want to use it, for whatever purpose, I should give it a name:

    $(".foo").on("click", function(myEvent){
      myEvent.preventDefault();
      myEvent.stopPropagation();
    });
    

    Now that I have granted myself access to the event details, I can prevent the default behavior that would result from the event, and I can also stop the event from bubbling up the DOM to other elements.

    Practical Example

    Suppose we wanted to listen for click events on an element:

    $("#bigSquare").on("click", function(event){
      /* Do something */
    });
    

    Click events happen on an element when you click the element itself, or any of its children. Now suppose this element had two children:

    Clicking any of these, the big square, the red square, or the blue square will cause the "click" event on the big square - after it causes the click event on whichever element you clicked first (events bubble up the DOM).

    We could determine which element was the target in any click event via the event itself:

    $("#bigSquare").on("click", function(event){
      alert( event.target.id );
    });
    

    Note here how we're accessing the ID of the target that raised the event. If you click on the red square, when that event bubbles up to the big square, we will see alerted "redSquare". The same goes for the blue square. If you click that, the event will bubble up to the big square and we will see alerted "blueSquare".

    You can test this online via the following demo: http://jsbin.com/ejekim/edit#javascript,live

    Try clicking the orange, red, or blue square to see what is alerted.

提交回复
热议问题