Home > Web Front-end > HTML Tutorial > Summary of JS Dom and events

Summary of JS Dom and events

php中世界最好的语言
Release: 2018-03-08 15:08:24
Original
1623 people have browsed it

This time I will bring you a summary of JS’s Dom and events, a summary of JS’s Dom and eventsWhat are the things to note?The following is a practical case, let’s take a look.

What is the difference between innerText and innerHTML of dom object?

innerHTML refers to the entire content from the starting position to the ending position of the object, including the Html tag .
innerText refers to the content from the starting position to the ending position, but it removes the Html tag.

What is the difference between elem.children and elem.childNodes?

Node (node) is the common name for any type of object in the DOM hierarchy. There are many types of Node, such as element nodes, attribute nodes, text nodes, comment nodes, etc. Element inherits the Node class, which means that Element is one of the many types of Node. That is, when NodeType is 1, Node is ElementNode. In addition, Element extends Node, and Element has attributes such as id, class, and children. children is an attribute of Element, and childNodes is an attribute of Node.

How many common methods are there to query elements?

There are three common ways to obtain elements, namely through element ID, through tag name and through class name.
1.getElementById
DOM provides a method called getElementById, which will return a node object corresponding to the id attribute.
2.getElementsByTagName
This method returns an array of objects (HTMLCollection to be precise, it is not an array in the true sense). Each object corresponds to a given tag in the document. of an element. Similar to getElementById, this method only provides one parameter, and its parameter is the name of the specified tag.
3.getElementsByClassName
In addition to obtaining elements by specifying tags, DOM also provides the getElementsByClassName method to obtain elements with specified class names.

How to create an element? How to set attributes to elements?

1.createElement(name) creates an element node
createElement() is a method in the Document object. This method returns an Element object based on the specified element name.
2. Set the attributes of the created element node
After creating the element, we may need to set the element attributes, such as setting CSS styles for the element, adding click events, etc. To set element attributes, you can use the setAttribute method of the Element object, or you can use the attribute name to set it.
3. Insert the element node into the specified position of the DOM document
After the element is created, you need to insert the element node into the specified position of the DOM document. To add an element, use the appendChild() method or insertBefore() method of the Element object. The appendChild()
method is to add a new child node to the element, and the added child node will be its last child node. The insertBefore() method is used to insert a new node before the existing node, and the added node will be a sibling node.

Adding or deleting elements?

Adding elements: Use createElement to add elements
Deleting elements: If you need to delete an HTML element, you must first obtain the parent element of the element, and then use removeChild to delete the corresponding element.

What is the difference between DOM0 events and DOM2 level event listening methods?

DOM0 event: DOM0 event refers to binding the event directly to the node. A node can only bind one event, otherwise the gray behind it will cover the previous one.
var oBtn = document.querySelctor('#btn');
oBtn.onclick=function(){
console.log('a')
};
DOM2 event: DOM2 Level events can bind multiple events to an element, and subsequent events will not overwrite previous events; you can use the parameters true and false to set the event to trigger in the bubbling phase or capture phase. Use removeEventListener to remove events.
oBtn.addEventListener("click",function(){
});
oBtn.removeEventListener("click",fn,false);

What is the difference between attachEvent and addEventListener?

1. Compatibility issues between addEventListener and attachEvent
addEventListener is an event binding method that complies with W3C specifications. FireFox, Chrome, and Safari all use it to bind events.
attachEvent is private to IE and does not comply with W3C specifications. Moreover, under IE, it can only be used to bind events, and addEventListener is invalid.
So, if you want to bind events, you must deal with compatibility issues.
2. Grammar rules for addEventListener and attachEvent
addEventListener has 3 parameters: element.addEventListener(type,listener,useCapture)
attachEvent has 2 parameters: element.attachEvent(type,listener);
3. Code compatibility processing
function regEvent(ele, event_name, fun)
{
if (window.attachEvent)
ele.attachEvent(event_name, fun); //IE browsing Device
else
{
event_name = event_name.replace(/^on/, “”); //If it starts with on, delete on, such as onclick->click
ele. addEventListener(event_name, fun, false); //Non-IE browser
}
}

Explain IE event bubbling and DOM2 event propagation mechanism?

IE event bubbling: The event occurs on the triggering element. Starting from the triggering element, the event is passed level by level to the parent element until the html element.
DOM2 events: Event propagation is divided into 3 stages, the capture stage, the event target stage, and the bubbling stage. The event listener can only choose to execute in one of the capture phase or the bubbling phase.
Capture phase: When an event occurs, it starts from the root node and searches down level by level to know the target element.
Bubbling stage: Starting from the triggering element, the event is passed level by level to the parent element until the html element

How to prevent event bubbling? How to prevent default event?

Prevent event bubbling: w3c’s method is e.stopPropagation(), and IE uses e.cancelBubble = true.
Prevent default events: w3c’s method is e.preventDefault(), and IE uses e.returnValue = false.

Q&A

There is the following code, which requires the console to display the text content of each element li when the element is clicked. Compatibility with

 <ul class="ct">
      <li>这里是</li>
      <li>饥人谷</li>
      <li>前端6班</li>
  </ul>
  <script>
  //todo ...
  </script>
Copy after login

is not considered Code:

<ul class="ct">
<li>这里是</li>
<li>饥人谷</li>
<li>前端6班</li>
</ul>
<script>
//方法一
/*var item = document.getElementsByClassName("ct")[0].getElementsByTagName(&#39;li&#39;)
for(var i=0;i<item.length;i++){
item[i].addEventListener(&#39;click&#39;, function(){
console.log(this.innerText);
})
} */
//方法二
var item = document.getElementsByTagName(&#39;li&#39;)
for(var i=0;i<item.length;i++){
item[i].addEventListener(&#39;click&#39;, function(){
console.log(this.innerText);
})
}
</script>
Copy after login

Completion code, requirements:

1. When clicking the button to add at the beginning, here is< ;/li> Add a new element before the element, the content is a non-empty string entered by the user; when clicking the end to add, add the user input after

  • Front End 6 Class
  • Non-empty string.
    2. When each element li is clicked, the console displays the text content of the element.

    <ul class="ct">
    <li>这里是</li>
    <li>555</li>
    <li>666</li>
    </ul>
    <input class="ipt-add-content" placeholder="添加内容"/>
    <button id="btn-add-start">开头添加</button>
    <button id="btn-add-end">结尾添加</button>
    <script>
    //todo ...
    </script>
    Copy after login

    Code:

    <ul class="ct">
    <li>这里是</li>
    <li>666</li>
    <li>555</li>
    </ul>
    <input class="ipt-add-content" placeholder="添加内容"/>
    <button id="btn-add-start">开头添加</button>
    <button id="btn-add-end">结尾添加</button>
    Copy after login
    <script>var ct = document.querySelector(&#39;.ct&#39;)var start = document.getElementById(&#39;btn-add-start&#39;);var end = document.getElementById(&#39;btn-add-end&#39;);var input = document.querySelector(".ipt-add-content");
         end.addEventListener(&#39;click&#39;,function(){            var list = document.createElement(&#39;li&#39;);        list.innerText = input.value        ct.appendChild(list);      })      start.addEventListener(&#39;click&#39;,function(){            var list = document.createElement(&#39;li&#39;);        list.innerText = input.value        ct.insertBefore(list,ct.firstChild);      })      ct.addEventListener(&#39;click&#39;, function(e){          if(e.target.tagName.toLowerCase() === &#39;li&#39;){           console.log(e.target.innerText);          }      });     </script>
    Copy after login

    Complete the code, requirement: when the mouse is placed on the li element, the data-img of the current li element will be displayed in img-preview corresponding picture.

     <ul class="ct">
          <li data-img="1.png">鼠标放置查看图片1</li>
          <li data-img="2.png">鼠标放置查看图片2</li>
          <li data-img="3.png">鼠标放置查看图片3</li>
      </ul>
      <div class="img-preview"></div>
      <script>
      //todo ...
      </script>
    Copy after login

    Code:

    <ul class="ct"><li data-img="http://img5.imgtn.bdimg.com/it/u=3425851328,2681317699&fm=21&gp=0.jpg">鼠标放置查看图片1</li><li data-img="http://pic24.nipic.com/20121003/10754047_140022530392_2.jpg">鼠标放置查看图片2</li><li data-img="http://img2.3lian.com/img2007/4/22/303952037bk.jpg">鼠标放置查看图片3</li></ul><div class="img-preview"></div><script>var ct = document.querySelector(&#39;.ct&#39;)var list = document.getElementsByTagName(&#39;li&#39;)var preview = document.querySelector(&#39;.img-preview&#39;)for(var i=0;i<list.length;i++){list[i].addEventListener(&#39;mouseover&#39;,function(){if(document.querySelector(&#39;img&#39;)){preview.removeChild(document.querySelector(&#39;img&#39;))console.log(1)}var item = document.createElement(&#39;img&#39;)var img = this.getAttribute(&#39;data-img&#39;)preview.appendChild(item)item.src=img;
        })      }    </script>
    Copy after login

    I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

    Related reading:

    How to use python to determine image similarity

    Javascript script used to download images

    The above is the detailed content of Summary of JS Dom and events. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template