JQ toggle Event switch

Jq object. Toggle (fn1, fn2...). When the component corresponding to the JQ object is clicked, fn1 is executed. When clicked the second time, fn2..... is executedCopy the code

⚠️ Note: in version 1.9, the.toggle() method is removed and the jQuery Migrate plugin can restore this function

<script src="https://cdn.bootcdn.net/ajax/libs/jquery-migrate/3.3.2/jquery-migrate.min.js"></script>
Copy the code
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>

<input type="button" value="Button" id="btn">
<script>
  $("#btn").toggle(
    () = > { console.log("First click")},() = > { console.log("Second click")},() = > { console.log("Third click")},</script>
Copy the code

Event triggering

  • 1 kind: object. Event name ()
  • 2 kinds ofTrigger (” event name “)
  • 3 kinds ofTriggerHandler (” Event name “)
<input type="text" id="txt">
<span></span>
<input type="button" value="Button" id="btn">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script>

  // The text box adds the event to get the focus
  $("#txt").focus(function () {$(this).next("span").text("Textbox gets focus.")   // Sets a prompt to be displayed in the next sibling of the current element
  })

  // Button points and events
  $("#btn").click(function () {
    // Type 1: call the focus event of the textbox
    // This lets events of other elements fire
    $("#txt").focus()

    // The second way is to trigger an event
    $("# TXT ").trigger("focus"

    // Can trigger this event, but not the default behavior of the browser
    $("#txt").triggerHandler("focus")})</script>

Copy the code

Binding of events

General: element. Event name (event handler)

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>

<input type="button" value="Button" id="btn">
<script>
  $("#btn")
    .mouseenter(function () {$(this).css("backgroundColor"."red")
    })
    .mouseleave(function () {$(this).css("backgroundColor"."green")
    })
    .click(function () {
      alert("Ahh, I've been clicked.")});</script>
Copy the code

The bind method binds events

Element. Bind (” event name “, event handler)

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>

<input type="button" value="Button" id="btn">
<script>
  $("#btn")
    .bind("click".function () {
      alert("Oh, buy thunder and thunder.")
    })
    .bind("mouseenter".function () {$(this).css("backgroundColor"."red")
    })
    .bind("mouseleave".function () {$(this).css("backgroundColor"."green")});</script>
Copy the code

Multiple events share a function

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>

<div id="btn">
  <input type="button" value="Button">
</div>
<script>
  $('#btn').bind('mouseover click'.function (event) {
    document.body.append($(this).html())
  })
</script>
Copy the code

Bind binds events in the form of key-value pairs

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>

<div id="btn">
  <input type="button" value="Button">
</div>
<script>
  $("#btn")
    .bind({
      "click": function () { alert("Oh, buy thunder and thunder.")},"mouseenter": function () {$(this).css("backgroundColor"."red")},"mouseleave": function () {$(this).css("backgroundColor"."green")}})</script>
Copy the code

Delegate delegate binding

Delegate (” child element selector “,” event name “, event handler) The final event is on the child element

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"</div> <input type="button" value=" child element "> </div> <input type="button" value=" button" id=" BTN" style="margin-top: 10px"> <script> $(function () {$("# BTN ").click(function () {$("# BTN ").click(function () {$("# BTN ").click(function () $(" # div "). The delegate (" input ", "click", function () {alert ("! </script>Copy the code

On the binding

Parent object. On (” event name “,” child element “, event handler)

<ul>
  <li>This is the first LI tag</li>
  <li>This is the second LI tag</li>
  <li>This is the third LI tag</li>
  <li>This is the fourth LI tag</li>
  <li>This is the fifth LI tag</li>
</ul>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script>
  $("ul").on("click"."li".function () {
    console.log(this, $(this) [0]) // These two are the same
  })
  setTimeout(() = >{$("ul").append("
  • This is number one"
  • + ($("ul").children().length + 1) + )},2000);
    </script> Copy the code

    ⚠️ Note: The last element added has the same click event

    You can call on() to bind events to yourself

    <input type="button" value="Binding" id="btn">
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
      $("#btn").on("click".function () {
        console.log("Ha ha, I'm handsome again.")})</script>
    Copy the code

    live

    <body>
      <p>This is a paragraph.</p>
      <p>Clicking on any P element will make it disappear. Including this paragraph.</p>
      <button>Insert a new P element after this button</button>
      <p><b>Note:</b>By using the live() method instead of the bind() method, the new p element also disappears when clicked.</p>
    </body>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    
    <script type="text/javascript">
      $(document).ready(function () {$("p").live("click".function () {$(this).slideToggle();
        });
        $("button").click(function () {$("<p>This is a new paragraph.</p>").insertAfter("button");
        });
      });
    </script>
    Copy the code

    The principle of event delegation

    <div></div>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
    
      // The functions of on and delegate are the same, but the order of the parameters is different
      setTimeout(() = >{$("

    This is a P

    "
    ).appendTo($("div")); }, 200) setTimeout(() = >{$(

    This is a P2

    "
    ).appendTo($("div")); }, 500The $()"div").on("click"."p".function () { alert($(this).text()) }); setTimeout(() = > { document.querySelector("#stopPropagation").addEventListener("click".(e) = > { e.stopPropagation() }, true)},2000); // After 2 seconds, the event bubbling is stopped, so id=stopPropagation can no longer call the parent element method
    </script>
    Copy the code

    Event delegation is to use the bubbling principle to add events to the parent level. By determining the subset of event sources and performing corresponding operations, event delegation can firstly greatly reduce the number of event binding and improve performance. Second, you can make new child elements have the same operation.

    Differences in event binding

    methods1Event name (event handler); methods2Bind (event name, event handler) method1And methods2There are two ways to bind events to existing elements that also have event objects. Delegate ()"Selector"."Event Name", event handler function)// The parent element calls the method, and the child element binds the eventCheck the object."Event Name"."Selector", event handler function)// The parent element calls the method, and the child element binds the eventBecause the delegate method is the method that calls on, you can just use onCopy the code

    Unbundling event

    Unbind () Unbind event

    <div>This is a div</div>
    <input type="button" value="Binding" id="btn1">
    <input type="button" value="Unbundling" id="btn2">
    
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
      $("#btn1").click(function () {$("div")
          .bind("click".function () {
            console.log("Div was clicked");
          })
          .bind("click".function () {
            console.log(Div dot second click);
          })
          .bind("mouseenter".function () {$(this).css("backgroundColor"."blue");
          })
          .bind("mouseleave".function () {$(this).css("backgroundColor"."yellow");
          })
          .click(function () {
            console.log("Ha ha"); $(})})"#btn2").click(function () {
        // Unbind click events, all click events are removed
        // $("div").unbind("click");
    
        // There are no arguments in parentheses, so all events of the element are unbound
        // $("div").unbind();
    
        // Unbind multiple events simultaneously
        $('div').unbind("mouseenter mouseleave")})</script>
    Copy the code

    Undelegate () undelegates events

    <div>This is a div</div>
    <input type="button" value="Binding" id="btn1">
    <input type="button" value="Unbundling" id="btn2">
    
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
      $("#btn1").click(function () {$("div")
          .click(function () {
            console.log("Div was clicked")
          })
          .mouseenter(function () {
            console.log("Mouse came in.")
          })
          .mouseleave(function () {
            console.log("Mouse away")
          })
          .append($("

    This is a P

    "
    )) // Create a p in div and bind the click event .delegate("p"."click".function () { console.log("Ah, p's been clicked.") }) .delegate("p"."mouseenter".function () { console.log("Mouse entry of P"The $()})})"#btn2").click(function () { // all events for p are removed // $("div").undelegate() // Remove p click events $("div").undelegate("p"."click") // Multiple events can be removed, but each event is separated by a space // $("div").undelegate("p", "click mouseenter") //div all events are gone // $("div").unbind() })
    </script> Copy the code

    Off () Unbind event

    <div>This is a div</div>
    <input type="button" value="Binding" id="btn1">
    <input type="button" value="Unbundling" id="btn2">
    
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
      $("#btn1").click(function () {$("div")
          .click(function () {
            console.log("Div was clicked")
          })
          .mouseenter(function () {
            console.log("Mouse came in.")
          })
          .mouseleave(function () {
            console.log("Mouse away")
          })
          .append($("

    This is a P

    "
    )) // Create a p in div and bind the click event .on("click"."p".function () { console.log("Ahh,p's been clicked.") }) .on("mouseenter"."p".function () { console.log("Ah, it's in p. Oh.") }) .on("click"."span".function () { console.log("Oh,span was clicked."The $()})})"#btn2").click(function () { // Unbind the click events of the parent and child elements //$("div").off("click"); // Multiple events for parent and child elements, separated by Spaces //$("div").off("click mouseenter"); // Unbind the click event for the p tag //$("div").off("click","p"); // both events of p are gone //$("div").off("click mouseenter","p"); // all events of p are unbound //$("div").off("","p"); // Kill click events for all child elements in div //$("div").off("click","**"); // All events of the parent and child elements are unbound $("div").off(); })
    </script> Copy the code

    <html>
      <body>
        <p>This is a paragraph.</p>
        <p>This is another paragraph.</p>
        <p>Click on any P element to increase size and word spacing. Include the paragraph.</p>
        <button>Removes the changeSize() event handler added to the p element via the live() method</button>
      </body>
    
    
      <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
      <script type="text/javascript">
        function changeSize() {$(this).animate({ fontSize: "+=3px" });
        }
        function changeColor() {$(this).animate({ letterSpacing: "+=2px" });
        }
        $(document).ready(function () {$("p").live("click", changeSize);
          $("p").live("click", changeColor);
          $("button").click(function () {$("p").die("click", changeSize);
          });
        });
      </script>
    </html>
    Copy the code

    Summary of event untying

    • What is the best way to bind events and what is the best way to unbind events
    • What’s the name of the event in the bind parentheses that will unbind that event, that will unbind multiple events that are clicked on that element
    • Object.click() can also be usedunbindunbundling
    • Without any arguments in parentheses, all events of the element are unbound
    • Unbind multiple events at the same time — just use a space between the name of each event

    The event bubbling

    Event attributes

    This property returns the target object that triggered the event, in this case a DOM object. E. currenttarget: This property returns the current object that triggered the event

    <div>
      <input type="button" value="Button">
    </div>
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
      console.log(window);
    
      $("div").on("click"."input".function (e) {
        //e.target: This property returns the target object that triggered the event, in this case a DOM object
        // e.currenttarget: This property gets the current object that triggered the event
        // e.delelegateTarget: This property returns the object of the proxy
        console.log(e, e.target, e.currentTarget, e.delegateTarget, $(e.currentTarget).attr("id"))
        console.log(e.screenX + "= = = =" + e.screenY)
      })
    </script>
    Copy the code

    Prevents events from bubbling

    JQ object

    <input type="button" value="Button" id="btn">
    
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.8.2/jquery.js"></script>
    <script>
      $("#btn").click(function (event) {
        console.log($(this).attr("id"))
    
        event.preventDefault()      // Block the default behavior for form submission
        event.stopPropagation()
        return false                // Return falese
      })
    </script>
    Copy the code

    The DOM object

    <input type="button" value="Button" id="btn">
    
    <script>
      document.getElementById("btn").onclick = function (e) {
        event.preventDefault()            // Block the default event
        e.stopPropagation()               // Google Firefox prevents events from bubbling
        window.event.cancelBubble = true  //IE8 prevents events from bubbling
      } 
    </script>
    Copy the code