1, Add / remove / replace / Clone
1. Add a new element
(1) DOM three steps
//a. Create a new empty object var element=document.createElement("Tag name") //b. Add required attributes element.Attribute name=Attribute value //c. Add a new element to the DOM tree //Append new element at the end Parent element.appendChild(New element) //Insert before existing element Parent element.insertBefore(New element, Existing element) //Replace existing element: Parent element.replaceChild(New element, Existing element)
(2) jQuery two steps
//a. Create multiple elements in batch with HTML fragments, and set the attributes and contents of the elements at the same time var $New element=$(`HTML fragment`) //b. Adding a new element to the DOM tree has 10 functions //Append a new element to the end of the parent element $Parent element.append($New element) //return $parent element $New element.appendTo($Parent element) //return $new element //Insert a new element at the beginning of the parent element $Parent element.prepend($New element) //return $parent element $New element.prependTo($Parent element) //return $new element //Insert before an existing element $Existing element.before($New element) //return $existing element $New element.insertBefore($Existing element) //return $new element //Insert after an existing element $Existing element.after($New element) //return $existing element $New element.insertAfter($Existing element) //return $new element //Replace existing element $Existing element.replaceWith($New element) //return $existing element $New element.replaceAll($Existing element) //return $new element
2. Delete element
$element.remove()
3. Clone elements
$element.clone()
For example: click the button to add a box and click × Delete the box;
<head> <style> .container { border: 1px solid #aaa; overflow: hidden; } .block { float: left; margin: 10px; border: 1px solid #aaa; background: #faa; width: 150px; height: 150px; } .block:hover { box-shadow: 0 5px 6px #000; } .close { float: right; padding: 5px; font-weight: bold; opacity: .2; cursor: pointer; } .close:hover { opacity: .5; } </style> </head> <body> <h1>add to/Delete node</h1> <button id="add-block">Add Block </button> <div></div> <script src="js/jquery-1.11.3.js"></script> <script> //1, Click the button to add a new box //DOM 4 steps //1. Find the element that triggers the event //Click the button to trigger the event because of the × Can be clicked, so use event delegate optimization. The event should only be bound to the parent element $("button") //2. Bind event handler .click(function () { //3. Find the element to modify //4. Modify elements //4.1 create a new box $(`<div><span>×</span></div>`) //4.2 setting random background color .css( "background-color", `rgb(${ parseInt(Math.random()*256) },${ parseInt(Math.random()*256) },${ parseInt(Math.random()*256) })` ) //4.3 add the new box to the beginning position under container div .prependTo(".container") }) //2, Delete the previously added box //DOM 4 steps //1. Find the element that triggers the event //Click the button to trigger the event because of the × Can be clicked, so use event delegate optimization. The event should only be bound to the parent element //Event delegation step 1: $(".container") //2. Bind event handler .click(function (e) { //Judge that if the currently clicked element has class close, the operation can continue //Step 2 of event delegation: replace this with e.target var $tar = $(e.target); //3. Find the element to modify //Step 3 of event delegation: judge the current element if ($tar.html() == "×") { $tar.parent() //4. Modify elements .remove(); } }) </script> </body>
As shown in the figure, click the "add block" button to add a random color box below, click " × "To delete the current box.
2, Events
1. Event binding
(1) There are three methods in DOM
a. Manual binding in HTML, but this method is cumbersome and inconvenient to maintain;
b. It is bound by assignment in js, but only one handler can be bound to an event;
c. Add an event listening object in js;
element.addEventListener("Event name",Event handler(){ ... }) element.removeEventListener("Event name",Original event handler(){ ... })
(2) There is a method in jQuery
$element.on("Event name",Event handler(){ ... }) $element.off("Event name",Original event handler) //Remove an event listener //Abbreviation $element.Event name(Event handler)
You can use a short list of common events:
eventmeaningeventmeaningblurLose focusmousemove Mouse movementclicksingle clickmouseoutMouse out (dom)dblclick
double-clickmouseover
Mouse entry (dom)focusGet focusmouseupMouse button liftkeydownKeyboard key pressresize window size changingkeyup
Keyboard key liftscroll Web page scrollingmousedownMouse button pressmouseleave
Mouse out (jq)mouseenter
Mouse entry (jq)It should be noted that functions with names are required to bind and remove events in jQuery. Multiple event listening objects can be bound at the same time, but all event handling functions with the same name will be removed at one time.
For example: click the button to launch bullets, which can launch a variety of bullets or remove bullets;
<body> <h1>Event binding</h1> <button id="btn1">Fire bullets</button> <button id="btn2">Get rewards</button> <button id="btn3">Loss of reward</button> <script src="js/jquery-1.11.3.js"></script> <script> //At btn1, ordinary bullets are fired $("#btn1").click(function () { console.log(`Fire ordinary bullets!`); }) var shoot2 = function () { console.log(`Get rewards+1`); } //When you click btn2, add a tracking missile to btn1 $("#btn2").click(function () { $("#btn1").click(shoot2); }) //At btn3, remove the tracking missile from btn1 $("#btn3").click(function () { $("#btn1").off("click", shoot2) }) </script> </body>
2. Event delegation in jquery
When multiple child elements at the same level are bound to the same event, event delegates are required.
(1) DOM event delegation three steps (key points)
a. The event is only bound to the parent element;
b.e.target instead of this ;
c. Determine whether the current target element is desired.
(2) jQuery event delegation three steps (understand)
a. The event is bound to the parent element, which must be bound in the on() method;
b. Instead of e.target instead of this, this in jQuery points to the target element actually clicked at first;
c. $parent element. on("click", "selector condition", event handler).
3. Automatically execute after the page is loaded
Because the web page is executed sequentially, the js code placed in the external js file is valid when imported at the end, and is invalid when imported at the beginning of the web page.
If you want js initialization, you can only execute it after the web page content is loaded. Do not execute it in advance. Use window ο nl ο ad=function() {}; usually placed in window ο nl ο No matter where the code in ad=function() {} is written, it will be automatically executed after the entire web page content is loaded (triggering the load event).
Examples are as follows:
<body> <button id="btn1">click me 1</button> <button id="btn2">click me 2</button> </body> <script> window.onload = function () { console.log(`Automatically execute when the page is loaded.`); $("#btn1").click(function () { console.log(`Don't order!`); }) $("#btn2").click(function () { console.log(`Warning again!!!`);; }) }) </script>
However, if both js files have window ο nl ο ad=function() {}, then only the window in the last imported js file ο nl ο ad=function() {} will be saved and overwritten. Therefore, a new writing method is used, which will save all windows ο nl ο Replace ad=function() {} with window.addEventListener("load",function() {});
It should also be noted that the load event can only be triggered after all web page contents (HTML+JS+CSS + pictures) are loaded. During web page loading, there are two loading completion events:
(1) First, only DOM content (HTML+JS) is loaded: DOMContentLoaded
(2) Then all web content is load ed
In the future, it should be bound to the DOMContentLoaded event as long as it does not depend on the initialization operation with css and pictures. It is as follows:
window.addEventListener( "DOMContentLoaded", function(){ ... } )
Abbreviation:
$(document).ready(function(){ ... }) $().ready(function(){ ... }) $(function(){ ... }) //Commonly used $(()=>{ ... })
For example: only when the DOM content is loaded, the button is bound with a click event in advance;
<body> <button id="btn1">click me 1</button> <button id="btn2">click me 2</button> </body> <script> //window.onload = function () { //window.addEventListener("load", function () { $(function () { console.log(`Automatically execute when the page is loaded.`); $("#btn1").click(function () { console.log(`Don't order!`); }) $("#btn2").click(function () { console.log(`Warning again!!!`);; }) }) // } //}) </script>
4. Mouse events
(1)DOM
mouseoverMouse entrymouseoutMouse awayEven if the above two methods repeatedly enter and exit the child element, the mouse in and out event on the parent element will be triggered repeatedly. There are some problems. The new event is:
mouseenter
Mouse entrymouseleaveMouse awaySimplified writing: if you bind both mouse in and mouse out events at the same time, you only need to bind a hover(), but it is only applicable in jQuery. The format is as follows:
$element.hover( //It is equivalent to mouse entering mouseenter and mouse moving out mouseleave function(){ ... }, //To mouseenter function(){ ... }, //Give mouseleave )
For example, use mouseenter and mouseover to bind mouse in and out events, and use hover to simplify mouse in and out events;
<body> <div id="target"> <p>Lorem ipsum dolor sit amet</p> </div> <script src="js/jquery-1.11.3.js"></script> <script> //When the mouse enters #target, add class hover; When the mouse leaves #target, remove the class hover // $("#target").mouseenter(function () { // $(this).addClass("hover") // }) // $("#target").mouseleave(function () { // $(this).removeClass("hover") // }) //Abbreviation $("#target").hover(function () { $(this).toggleClass("hover") //The replacement function toggleClass indicates that mouseenter and mouseleave are switched }) </script> </body>
5. Analog trigger
Even if there is no point on the button, the click event handler on the button can be triggered.
$element.trigger("Event name")
If the event to be triggered belongs to the common event list, you can also omit trigger(), which is abbreviated as:
$element.Event name()