Sharp JQuery Learning Events in JQuery

1. Load the DOM

After the page is loaded, the browser will add events to the dom element through javascript, using the window.onload method in regular javascript and the $(document).ready(); method in jQuery. This method replaces the window.onload() method in javascript and can greatly improve the response speed of web applications. Through this method, you can operate on the dom and call the events bound to it when it is ready.

the difference:

1. Execution time

window.onload(): All elements in the web page can be manipulated after they are loaded into the browser

$(document).ready(): You can operate on the DOM element after it is ready, without waiting for all associated files to be downloaded

2. Multiple references

window.onload(): Only a reference to one function can be saved at a time. If it is referenced multiple times, the latter function will overwrite the former;

$(document).ready(): Each call will append a new behavior to the existing behavior, and these behavior functions will be executed in sequence according to the registration order;

In layman's terms, when called multiple times, the former only takes effect for the last call, while the latter takes effect all, and the functions (events) within it are executed according to the calling order.

3. Shorthand

There is a shorthand for jquery only:

$(document).ready(function(){});  ==   $(function(){});

2. Event binding

1. Binding method: bind (event type, parameters, execution function)

事件类型有blur/focus/load/resize/scroll/unload/click/dblclick/mousedown/mouseup/mousemove/mouseover/mouseout/mouseenter/mouseleave/change/selsect/

submit/keydown/keypress/keyup/error, etc., can also be customized, but I have not tried the customized method! !

2. When operating on the same element, you can use chained operations to bind multiple events

3. Abbreviation

Take the click event as an example: $(ele).bind("click",function(){}); == $(ele).click(function(){});

3. Synthetic events

jQuery has two synthetic events: hover() and toggle()

1. hover(enter, leave): simulates a mouseover event, executes enter when the cursor moves into the element, and executes the leave function when the cursor moves out

2. toggle(fun1,fun2,fun3..): Simulate continuous mouse click events, and execute the bound functions in turn in turn

Precautions:

1⃣️hover simulates mouseenter and mouseleave functions, not mouseover and mouseout functions, so when triggering the leave method in hover, you need to call trigger("mouseleave");

2⃣️The pseudo-class selector in CSS: hover can also achieve the effect of changing the appearance of elements when the mouse is hovered;

Fourth, event bubbling and event capture

After reading a lot of explanations, according to my own understanding, event bubbling and event capture are both for the case where elements are nested and bound to the same event. in:

Event bubbling: It means that when the event bound to the inner element is triggered, the event of the element and its parent element will be triggered and executed sequentially from the inside out;

Event capture: It means that when the event bound to the inner element is triggered, the event of the element and its parent element will be triggered, and the events will be executed sequentially from outside to inside;

The difference between them is the order in which the events are fired.

for example:

1. Event Bubbling

Event bubbling will first capture the same event triggered from the outermost element, stop on the element that triggered the event, and then bubbling from the inside out, it is first captured and then bubbling.

Step 1: Create Nested Elements

<div class="div2">
        <h4>Test event bubbling</h4>
        <div class="div21"> I am the first div
             <div class="div22">
                i am the second div
                <span class="div23" style="display: block;">我是span</span>
            </div>
        </div>
</div>

Step 2: Bind the click event

$(".div2").bind("click",function(event){
    console.info( "I am the parent div" );
});
$(".div21").bind("click",function(event){
    console.info( "I am the first div" );
});
$(".div22").bind("click",function(event){
    console.info( "I am the second div" );
});
$(".div23").bind("click",function(event){
    console.info( "I am span" );
});
    

The third step, click on the innermost element, test the result

Step 4: Stop the event from bubbling

There are two ways to prevent event bubbling: event.stopPropagation() and return false; stop bubbling at the penultimate element in the above example, then click on the innermost element, and the event will be executed to the second div Then stop the execution, that is, stop the bubbling.

// Event bubbling: bind events to div2 and inner elements 
    $(".div2").bind("click", function (event){
        console.info( "I am the parent div" );
         /* console.info("Event type: "+event.type);
        console.info("The element that triggered the event: "+event.target); */
    })
    $(".div21").bind("click",function(event){
        console.info( "I am the first div" );
         /* console.info("The element that triggered the event: "+event.target);
        event.preventDefault();//This place is useless, because bubbling is not the default behavior
        return false; */
    })
    $(".div22").bind("click",function(event){
        console.info( "I am the second div" );
         /* console.info("The element that triggered the event: "+event.target); */
        event.stopPropagation();
    })
    $(".div23").bind("click",function(event){
        console.info( "I am span" );
         /* console.info("The element that triggered the event: "+event.target);
        // stop the event from bubbling
        event.stopPropagation(); */
    });

Click on the innermost element to view the renderings

It can be seen that the bubbling stops when the penultimate div is executed.

2. Event capture

The event capture will traverse from the outermost element inward, and execute when the same event is captured, and stop capturing at the element that triggered the event.

Step 1: Create Nested Elements

<div class="div3" id="div3">
        <h4>Test event capture</h4>
        <div class="div31" id="div31">我是第一个div
            <div class="div32" id="div32">
                i am the second div
                <span class="div33" id="div33" style="display: block;">我是span</span>
            </div>
        </div>
</div>

Step 2: Bind the event

Note: jQuery does not support event capture, so it can only be implemented with native js. Event bubbling can also be implemented with native js. When the third parameter is false, it is event bubbling, and when it is true, it is event capture, as shown below:

// Event capture: The parameters are event name event body capture (true) OR bubbling (false or default) 
    // Jquery does not support event capture, only native js 
    document.getElementById("div3").addEventListener(" click", function (e){
        console.info( "I am the parent div" );
    },true);
    document.getElementById("div31").addEventListener("click",function(e){
        console.info( "I am the first div" );
    },true);
    document.getElementById("div32").addEventListener("click",function(e){
        console.info( "I am the second div" );
    },true);
    document.getElementById("div33").addEventListener("click",function(e){
        console.info( "I am span" );
    },true);

Step 3: Click on the innermost element to view the effect

In the above execution result, events are executed sequentially from outside to inside.

Step 4: Execute return false at the first div to stop event capture

// Event capture: The parameters are event name event body capture (true) OR bubbling (false or default) 
    // Jquery does not support event capture, only native js 
    document.getElementById("div3").addEventListener(" click", function (e){
        console.info( "I am the parent div" );
    },true);
    document.getElementById("div31").addEventListener("click",function(e){
        console.info( "I am the first div" );
         return  false ; // This method cannot prevent event capture 
    }, true );
    document.getElementById("div32").addEventListener("click",function(e){
        console.info( "I am the second div" );
        e.stopPropagation(); // This method can prevent event capture 
    }, true );
    document.getElementById("div33").addEventListener("click",function(e){
        console.info( "I am span" );
    },true);

In the above code, I use return false; at the first div to stop the event from not being captured, and use stopPropagation() at the second div to stop the event capture, and now click on the innermost span element to see the effect as follows :

Judging from the execution results, return false does not have the effect of preventing event capture, so the stopPropagation() method should be used to stop event bubbling and event capture;

Finally, there is a method to prevent the execution of the default behavior of the event, which is the preventDefault() method. For example, to illustrate the usefulness of this method:

When the button in a form is of the submit type, if we click the button, the form will be submitted, but sometimes we need to verify the form, for example, the user name and password cannot be empty, if they are empty, the form cannot be submitted. If the control form cannot be submitted, you can use the preventDefault() method, or you can use rerurn false. From personal experience, return false is more often used.

Five, the properties of the event object

1. event.type to get the event type

2. event.preventDefault() prevents the occurrence of the default behavior of the event

3. event.stopPropagation() prevents events from bubbling

4. event.target gets the element that triggered the event

5. event.relatedTarget Gets the related elements of the event

6. event.pageX event.pageY Get the x-coordinate and y-coordinate of the cursor relative to the page

7. event.which obtains the left, middle and right keys of the mouse in the mouse stand-alone event, and obtains the keys of the keyboard in the keyboard event, that is, which key is pressed, the key value of this key is obtained

8. event.metaKey gets the ctrl key in keyboard events

6. Others

1. Event removal

Using the unbind method, you can remove all bound events, and you can also remove the specified event. When removing the specified event, you want to define the name of the event when binding.

As follows:

   // Binding events: bind multiple events and assign different function names 
    $(".div52").bind("click", fun1 = function (){
        console.info( "I am the first event" );
    }).bind("click",fun2 = function(){
        console.info( "I am the second event" );
    }).bind("click",fun3 = function(){
        console.info( "I am the third event" );
    });
    
    // Remove the event: remove the specified event according to the event name 
    $(".div51").hover( function (){
        $(".div52").unbind("click",fun1);
    },function(){
        $(".div52").unbind("click",fun3);
    });

Reminder: If there is a need to be removed after an event is executed once, and no longer triggered after that, you can use the one method

// Bind and unbind the event: the bound event is removed once it is executed 
    $(".div53").one("click", function (){
        console.info( "I only trigger once" );
    }).one("mouseover",function(){
            console.info( "Mouse in" );
    }).one("mouseout",function(){
            console.info( "Mouse out" );
    });

2. Event trigger

How to use trigger (event type)

3. Pass data

When binding events, you can pass parameters to functions and use them in the function body

4. Bind multiple events to an element

You can use chaining or separate event types with spaces. The former can implement different operations for different event types, and the latter can accomplish the same function for different types of events.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325442344&siteId=291194637