1.1. Node Operations
1.1.1 Deleting a Node
The node.removechild () method removes a child node from a node node and returns the removed node.
< button > delete < / button ><ul>
<li>Big bear</li>
<li>Two bears</li>
<li>Baldheaded stronger</li>
</ul>
<script>
// 1. Get the element
var ul = document.querySelector('ul');
var btn = document.querySelector('button');
// 2. Remove element node.removechild (child)
// ul.removeChild(ul.children[0]);
// 3. Click the button to delete the children in turn
btn.onclick = function() {
if (ul.children.length == 0) {
this.disabled = true;
} else {
ul.removeChild(ul.children[0]); }}</script>
Copy the code
1.1.2 Case: Deleting a Message
<textarea name="" id=""></textarea>
<button>release</button>
<ul>
</ul>
<script>
// 1. Get the element
var btn = document.querySelector('button');
var text = document.querySelector('textarea');
var ul = document.querySelector('ul');
// 2. Register events
btn.onclick = function() {
if (text.value == ' ') {
alert('You did not enter anything');
return false;
} else {
// console.log(text.value);
// (1) Create element
var li = document.createElement('li');
// Li can be assigned first
li.innerHTML = text.value + " delete < / a >";
// (2) Add elements
// ul.appendChild(li);
ul.insertBefore(li, ul.children[0]);
// (3) Delete element deletes the parent of the current link li
var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
Li this.parentNode; li this.parentNode;
ul.removeChild(this.parentNode); }}}}</script>
Copy the code
1.1.3 Copying (Cloning) a Node
<ul>
<li>1111</li>
<li>2</li>
<li>3</li>
</ul>
<script>
var ul = document.querySelector('ul');
// 1. node.cloneNode(); The parentheses are empty or the inside is false. Shallow copy copies only the tag, not the inside
// 2. node.cloneNode(true); The parentheses are true. The deep copy copy tag copies the contents inside
var lili = ul.children[0].cloneNode(true);
ul.appendChild(lili);
</script>
Copy the code
1.1.4 Case: Dynamically Generating tables
<script>
// 1. Prepare students' data first
var datas = [{
name: 'Wei Yingluo'.subject: 'JavaScript'.score: 100
}, {
name: 'hong li'.subject: 'JavaScript'.score: 98
}, {
name: 'Fu Heng'.subject: 'JavaScript'.score: 99
}, {
name: 'MingYu'.subject: 'JavaScript'.score: 88
}, {
name: 'Big pig trotter'.subject: 'JavaScript'.score: 0
}];
// 2. Create a row in tBody: We will create a few rows for the number of people (by the length of the array)
var tbody = document.querySelector('tbody');
// go through the number group
for (var i = 0; i < datas.length; i++) {
// 1. Create the tr line
var tr = document.createElement('tr');
tbody.appendChild(tr);
// 2. The number of td cells in a row depends on the number of attributes in each object
// Use for in to traverse the student object
for (var k in datas[i]) {
// Create a cell
var td = document.createElement('td');
// Add datas[I][k] to td
td.innerHTML = datas[i][k];
tr.appendChild(td);
}
// 3. Create cell with delete 2 words
var td = document.createElement('td');
td.innerHTML = ' delete < / a > ';
tr.appendChild(td);
}
// 4. The deletion operation begins
var as = document.querySelectorAll('a');
for (var i = 0; i < as.length; i++) {
as[i].onclick = function() {
Node.removechild (child)
tbody.removeChild(this.parentNode.parentNode)
}
}
</script>
Copy the code
1.1.5 Three ways to create an element
<script>
// There are three different ways to create elements
// 1.document.write () create element If the page document flow has been loaded, calling this statement will cause the page to be redrawn
var btn = document.querySelector('button');
btn.onclick = function() {
document.write('<div>123</div>');
}
// 2. InnerHTML creates the element
var inner = document.querySelector('.inner');
for (var i = 0; i <= 100; i++) {
inner.innerHTML += '
}
var arr = [];
for (var i = 0; i <= 100; i++) {
arr.push(');
}
inner.innerHTML = arr.join(' ');
// 3. Document.createelement () creates the element
var create = document.querySelector('.create');
for (var i = 0; i <= 100; i++) {
var a = document.createElement('a');
create.appendChild(a);
}
</script>
Copy the code
1.1.6 Efficiency comparison between innerTHML and createElement
InnerHTML string concatenation (inefficient)
<script>
function fn() {
var d1 = +new Date(a);var str = ' ';
for (var i = 0; i < 1000; i++) {
document.body.innerHTML += '
';
}
var d2 = +new Date(a);console.log(d2 - d1);
}
fn();
</script>
Copy the code
CreateElement method (low efficiency)
<script>
function fn() {
var d1 = +new Date(a);for (var i = 0; i < 1000; i++) {
var div = document.createElement('div');
div.style.width = '100px';
div.style.height = '2px';
div.style.border = '1px solid red';
document.body.appendChild(div);
}
var d2 = +new Date(a);console.log(d2 - d1);
}
fn();
</script>
Copy the code
InnerHTML array method (efficient)
<script>
function fn() {
var d1 = +new Date(a);var array = [];
for (var i = 0; i < 1000; i++) {
array.push('
');
}
document.body.innerHTML = array.join(' ');
var d2 = +new Date(a);console.log(d2 - d1);
}
fn();
</script>
Copy the code
1.2. Core summary of DOM
With respect to DOM manipulation, we focus on manipulation of elements. There are mainly create, add, delete, change, check, attribute operation, event operation.
1.2.1. Create
1.2.2. Added
1.2.3. Delete
1. Change
Check 1.2.5.
1.2.6. Property operations
1.2.7. Event Operations (key)
1.3. Advanced Events
1.3.1. Register events (2 ways)
1.3.2 Event Listening
AddEventListener () Event listener (supported after IE9)
EventTarget. AddEventListener () method specifies the listeners registered to the eventTarget (target), when the object trigger event is specified, the event handler should be executed.
AttacheEvent () Event Listener (supported by IE678)
The eventTarget.attachevent () method registers the specified listener with the eventTarget (the target object), and when that object fires the specified event, the specified callback function is executed.
<button> Traditional registration event </button><button>Method listens for registration events</button>
<button>ie9 attachEvent</button>
<script>
var btns = document.querySelectorAll('button');
// 1. Register events the traditional way
btns[0].onclick = function() {
alert('hi');
}
btns[0].onclick = function() {
alert('hao a u');
}
// 2. Register event addEventListener
// The event type inside (1) is the string must be quoted without on
// (2) Add more listeners to the same element and event
btns[1].addEventListener('click'.function() {
alert(22);
})
btns[1].addEventListener('click'.function() {
alert(33);
})
AttachEvent Supported by earlier Versions of Internet Explorer 9
btns[2].attachEvent('onclick'.function() {
alert(11);
})
</script>
Copy the code
Event listening compatibility solution
Encapsulate a function that determines the browser type:
1.3.3. Delete Event (Unbind event)
<div>1</div>
<div>2</div>
<div>3</div>
<script>
var divs = document.querySelectorAll('div');
divs[0].onclick = function() {
alert(11);
// 1. Delete events in the traditional way
divs[0].onclick = null;
}
// 2. RemoveEventListener Deletes the event
divs[1].addEventListener('click', fn) // Fn inside does not need to be called with parentheses
function fn() {
alert(22);
divs[1].removeEventListener('click', fn);
}
// 3. detachEvent
divs[2].attachEvent('onclick', fn1);
function fn1() {
alert(33);
divs[2].detachEvent('onclick', fn1);
}
</script>
Copy the code
** Remove event compatibility solution **
1.3.4. DOM event flow
The tags in HTML are nested within each other. We can think of elements as a box inside a box, and the document is the big outer box. When you click on a div, you also click on the parent element of the div, or even the entire page. Do you execute the parent element click event first, or the div click event first?Copy the code
For example, we registered a click event for a div on the page, and when you click div, you click Body, you click HTML, and you click Document.
At that time two big browser overlords who also disobey who! IE proposes to start with the target element and then receive and respond to the event layer by layer, a bubbling event stream. Netscape proposed to start at the outermost layer and then receive and respond to events, layer by layer, in what is called a captured event stream. River's lake dispute, wu Lin league Lord also head ache!! In the end, the W3C took a middle ground and settled on a common standard -- capture first, bubble later. Modern browsers follow this standard, so when an event occurs, it goes through three phases.Copy the code
The DOM event flow goes through three stages:
-
Capture phase
-
Current target stage
-
Bubbling phase
If we throw a stone into the water, it will first have a descent process, which can be understood as the capture process from the topmost layer to the most specific element of the event (the target point); Bubbles are then created and float to the surface of the water after the lowest point (the most specific element), a process equivalent to event bubbling.
The event bubbling
<div class="father">
<div class="son">Son box</div>
</div>
<script>
// Onclick and attachEvent (ie) fire in the bubbling phase
If the third addEventListener parameter is false or omitted
// son -> father ->body -> html -> document
var son = document.querySelector('.son');
// Register the son click event
son.addEventListener('click'.function() {
alert('son');
}, false);
// Register the father click event
var father = document.querySelector('.father');
father.addEventListener('click'.function() {
alert('father');
}, false);
// Register the document click event, omitting the third argument
document.addEventListener('click'.function() {
alert('document');
})
</script>
Copy the code
Event capture
<div class="father">
<div class="son">Son box</div>
</div>
<script>
// If the third addEventListener() argument is true then it is emitted during the capture phase
// document -> html -> body -> father -> son
var son = document.querySelector('.son');
// Register the son click event with the third parameter true
son.addEventListener('click'.function() {
alert('son');
}, true);
var father = document.querySelector('.father');
// Register the click event for father with the third parameter true
father.addEventListener('click'.function() {
alert('father');
}, true);
// Register the document click event with the third parameter true
document.addEventListener('click'.function() {
alert('document');
}, true)
</script>
Copy the code
1.3.5. Event objects
What is an event object
After an event occurs, the collection of information data related to the event is put into this object, which is the event object.
Such as:
-
Who bound this event.
-
When the mouse triggers an event, it gets information about the mouse, such as its position.
-
When the keyboard triggers an event, it gets information about the keyboard, such as which key was pressed.
Use of event objects
Event objects are generated when an event firing occurs and are passed by the system as arguments to the event handler.
Therefore, declare a parameter in the event handler to receive the event object.
Event object compatibility handling
The event object itself has compatibility issues:
-
In standard browsers, the parameters passed by the browser to the method can be obtained by defining parameter E.
-
In IE6~8, the browser does not pass parameters to methods. If necessary, you need to go to window.event to look for them.
As long as the "| |" false front, no matter "| |" behind is true or false, return "| |" at the back of the value. Front is true, as long as the "| |" no matter "| |" behind is true or false, return "| |" in front of the value.Copy the code
<div>123</div>
<script>
var div = document.querySelector('div');
div.onclick = function(e) {
// Event object
e = e || window.event;
console.log(e);
}
</script>
Copy the code
Properties and methods of the event object
The difference between e.target and this
-
This is the element of the event binding (the element that binds the event handler).
-
E.target is the element that triggers the event.
Usually terget and this are the same, but when the event bubbles (the parent element has the same event, and clicking on the child element triggers the parent element's event handler), this refers to the parent element because it is the element object to which the event is bound. Target refers to the child element because it is the specific element object that triggered the event.Copy the code
<div>123</div>
<script>
var div = document.querySelector('div');
div.addEventListener('click'.function(e) {
// e.target and this refer to divs
console.log(e.target);
console.log(this);
});
</script>
Copy the code
Events bubble under E.target and this
<ul>
<li>abc</li>
<li>abc</li>
<li>abc</li>
</ul>
<script>
var ul = document.querySelector('ul');
ul.addEventListener('click'.function(e) {
// we bind the event to ul so this points to ul
console.log(this); // ul
// e.target is the object that triggered the event. We clicked on Li
console.log(e.target); // li
});
</script>
Copy the code
1.3.6 Prevent default behavior
Some tags in the HTML have default behaviors. For example, after a tag is clicked, the page is redirected by default.
<a href="http://www.baidu.com"> baidu < / a ><script>
// 2. Prevent the default behavior from skipping links
var a = document.querySelector('a');
a.addEventListener('click'.function(e) {
e.preventDefault(); // dom standard
});
// 3. Traditional registration method
a.onclick = function(e) {
// common browser e.preventdefault (); methods
e.preventDefault();
// Lower version Browser IE678 returnValue property
e.returnValue = false;
// We can also use return false to prevent the default behavior from being incompatible
return false;
}
</script>
Copy the code
1.3.7 Preventing Events from bubbling
The nature of the event bubble itself will bring both harm and good.
<div class="father">
<div class="son">Son son</div>
</div>
<script>
var son = document.querySelector('.son');
// Register the son click event
son.addEventListener('click'.function(e) {
alert('son');
e.stopPropagation(); // stop Stops Propagation
window.event.cancelBubble = true; // Nonstandard Cancel Cancels bubble
}, false);
var father = document.querySelector('.father');
// Register the father click event
father.addEventListener('click'.function() {
alert('father');
}, false);
// Register the document click event
document.addEventListener('click'.function() {
alert('document');
})
</script>
Copy the code
Compatibility handling to prevent event bubbling
1.3.8 Event Delegation
The nature of the event bubble itself will bring both harm and good.
What is event delegation
Delegate the matter to someone else.Copy the code
Event delegates are also called event proxies, or event delegates in jQuery.
In plain English, you do not register events for child elements, register events for parent elements, and execute the processing code in the event of the parent element.
Agents in life:
Proxy in js events:
The principle of event delegation
Register events for the parent element and use event bubbling. When the child element’s event is triggered, it will bubble to the parent element and then control the corresponding child element.
The role of event delegation
-
We only manipulated the DOM once, improving the performance of the program.
-
Dynamically newly created child elements also have events.
<ul>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
<li>You know what? I should have a frame in hand!</li>
</ul>
<script>
// The core principle of event delegation is to add listeners to the parent node and use event bubbling to affect each child node
var ul = document.querySelector('ul');
ul.addEventListener('click'.function(e) {
// e.target this will get the object we clicked on
e.target.style.backgroundColor = 'pink';
})
</script>
Copy the code
1.4. Common mouse events
1.4.1 Case: Disable text selection and right-click menu
<body> I'm a text I don't want to share <script>// contextMenu we can disable the right menu
document.addEventListener('contextmenu'.function(e) {
e.preventDefault();
})
// 2. Disable selectStart
document.addEventListener('selectstart'.function(e) {
e.preventDefault();
})
</script>
</body>
Copy the code
1.4.2 Mouse Event Object
1.4.3 Obtaining the coordinates of the mouse on the page
<script>
// the MouseEvent object MouseEvent
document.addEventListener('click'.function(e) {
// 1. The client mouse is in view of the x and Y coordinates
console.log(e.clientX);
console.log(e.clientY);
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');
// 2. Page Indicates the x and Y coordinates of the page document
console.log(e.pageX);
console.log(e.pageY);
console.log('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -');
// 3. The mouse is in the x and Y coordinates of the computer screen
console.log(e.screenX);
console.log(e.screenY);
})
</script>
Copy the code
1.4.4 Case: Angel following the mouse
<img src="images/angel.gif" alt="">
<script>
var pic = document.querySelector('img');
document.addEventListener('mousemove'.function(e) {
// 1. Mousemove will trigger this event whenever the mouse moves 1px
// 2. Core principle: Every time the mouse moves, we will get the latest mouse coordinates,
// Use the x and y coordinates as the top and left values to move the image
var x = e.pageX;
var y = e.pageY;
console.log(The x-coordinate is zero. + x, 'The y-coordinate is'. + y);
//3. Don't forget to add px units to left and top
pic.style.left = x - 50 + 'px';
pic.style.top = y - 40 + 'px';
});
</script>
Copy the code