JS life from scratch -- BOM, DOM and events in JS

Keywords: Attribute Javascript IE ftp

According to the previous reply, variables, operators, branches, loops and nested loops in JS. This time, Ben K will nag everyone about BOM, DOM and events in JS.

1, "Flower heart Radish" -- BOM

1. Shocked, why FFF group raised the torch to BOM -- Introduction to BOM

BOM(Browser Object Model) refers to the browser object model. In JS, BOM is a big turnip, because it has many objects. Among them, the Window object representing the browser Window is the "main room" of BOM, that is, the most important one. Other objects are the beginning of the main room, or the side room.

2. Details of BOM objects

2.1 the main room of BOM - window object.

Window object represents browser window, which is the most commonly used object in JS BOM. Now I will introduce the common methods to understand window object.

① prompt: pop up window accepts user input;
② alert: pop up warning;
③ Confirm: prompt box with confirm / Cancel button;
④ Close: close the browser window;
⑤ open: reopen a new window, pass in the parameter URL / window name / window feature;
⑥ setTimeout: set delay execution, only once (two parameters: function to be executed / millisecond);
⑦ setInterval: set the timer, and execute the cycle every N milliseconds (input parameter: return an ID when calling setInterval, accept the ID through variable, and input clearInterval);
⑧ clearTimeout: clear delay;
⑨ clearInterval: clear timer;

Among the nine methods, the four most commonly used and troublesome are setTimeout/clearTimeout and setInterval/clearInterval, which are two corresponding methods and often used together. Here's a chestnut for you~

(Chestnut: setTimeout/clearTimeout)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>First of all setTimeout And clearTimeout</title>
        <!--Remember to open the console first~-->        
        <script type="text/javascript">
           var timeoutid = setTimeout(function(){
                console.log("setTimeout");
            },5000) ;
            function clearTimeoutBtn(){
                clearTimeout(timeoutid);
            }
        </script>
    </head>
    <body>
        <button onclick="clearTimeoutBtn()">clearTimeout</button>
    </body>
</html>

(Chestnut: setInterval/clearInterval)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>And then there was setInterval And clearInterval</title>
        <!--Remember to open the console first~-->
        <script type="text/javascript">
            var num = 10;
            var timeinterval = setInterval(function(){
                num--;
                console.log(num);
                if (num==0){
                clearInterval(timeinterval);
                }
            },1000)
            function clearIntervalBtn(){
                clearInterval(timeinterval);
            }
        </script>
    </head>
    <body>
        <button onclick="clearIntervalBtn()">clearIntervar</button>
    </body>
</html>

2.2 BOM siderooms - brief introduction of other objects.

Because other BOM objects except window objects seldom appear in the actual JS writing, this K will give you a brief introduction in the form of code.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>BOM The siderooms of</title>
        <!--Remember to open the console first~-->
        
        <script type="text/javascript">
            
            // screen object
            
            console.log(screen);
            console.log(screen.width);//width
            console.log(screen.height);//height
            console.log(screen.availHeight);//Available height=Screen height-Bottom taskbar
            console.log(screen.availWidth);//Available width
            
            // location object
            //   complete url route: 
            //   agreement:// Host name (IP address): port number (default 80 port) / file path parameters passed (parameter name 0 = parameter value 0 & parameter name 1 = parameter value 1) × anchor
            
            console.log(location);
            console.log(location.href);//Full path
            console.log(location.protocol);//Path protocol http: https: ftp: file: mailto: 
            console.log(location.pathname);//Path part  /start
            console.log(location.port);//Port number
            console.log(location.search);//from?Start later
            console.log(location.hostname);//IP address
            console.log(location.host);//host name+Port number
            console.log(location.hash);//from#Starting anchor
            // use JS Set page Jump
            //    window.location="http://www.baidu.com";
            
            function locationReload(){
                //Reload current page
                location.reload(true);//reload(true)Indicates that the current page is reloaded from the server; reload()Refresh the current page locally
            }
            
            function locationAssign(){
                location.assign("http://www.baidu.com");    //Load a new document, and you can back off after replacement
            }
            
            function locationReplace(){
                location.replace("http://www.baidu.com");//Replace the current document with a new document, and it cannot be rolled back after replacement
            }
            
            // history
            // length : Number of browsing history lists
            // history.forward(); :  Go to previous page
            // history.back(); :  Back to the next page
            // history.go(); : Jump to any position in the history browsing history; the current page is 0, the previous page is 1, and the next page is-1 individual
            
            console.log(history.length);
            
            function historyForword(){
                history.forward();
            }
            function historyBack(){
                history.back();
            }
            function historyGo(){
                history.go();
                // 0 
                // 1 = history.forward();
                // -1 = history.back();
            }
            
            // Navigator
            console.log(navigator.appName);//Product name
            console.log(navigator.appVersion);//Product version number
            console.log(navigator.userAgent);//User agent information
            console.log(navigator.platform);//System agent platform
            
            console.log(navigator.plugins);//Check the plug-in information installed by the browser
            // Returns an array to check all the plug-ins installed by the browser(↓Main attributes↓)
            // description :  Plug in description
            // filename :  File name of plug-in on local disk
            // length :  Number of plug-ins
            // name :  file name
        
            console.log(navigator.mimeTypes);//File types supported by browser plug-ins(↓Main attributes↓)
            // description: MIME Type description
            // enabledPlugin: Supports this type of browser plug-in
            // suffixes: Possible suffixes for this type
            // type: MIME Type, for example: image/x-icon text/css
        </script>
        
    </head>
    <body>
        
        <button onclick="locationAssign()">Load new document</button>
        <br />
        
        <button onclick="locationReload()">Reload current document</button>
        <br />
        
        <button onclick="locationReplace()">Replace the current document with a new document</button>
        <br />
        
        <button onclick="historyForword()">This is historyForword</button>
        <br />
        
        <button onclick="historyBack()">This is historyBack</button>
        <br />
        
        <button onclick="historyGo()">This is historyGo</button>
        
    </body>
</html>

2, "The same generation in N" -- DOM

1. Chaoyang people make contributions again, so mysterious "huge organization" appears in the code -- Introduction to DOM

DOM (Document Object Model), which refers to the Document Object Model, is the standard programming interface for dealing with extensible markup language recommended by W3C organization. On the web page, the objects organizing the page (or document) are organized in a tree structure to represent the standard model of the objects in the document, and each branch of DOM is called a "node", and the structure chart composed of all nodes and node attributes will show a strong hierarchy (chestnut is shown in the figure below, from the omnipotent nun).

DOM nodes are divided into three categories: element node, text node and attribute node. Text node and attribute node are two sub nodes of element node. Element node can be obtained through gelElement series method.

2. The truth of such an organization is... -- a detailed explanation of DOM operation

DOM operation is a very strong part of JS, so this K will tell you in the form of code.

2.1 get node and style modification

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM Code details (1)</title>
        
        <script type="text/javascript">            

            
            window.onload = function(){
                var div1 = document.getElementById("div1");//adopt ID Get a unique node; multiple nodes with the same name ID Only the first
                console.log(div1);
                
                console.log(div1.tagName);//View nodes:①Attribute; get the label name of the node
                console.log(div1.innerHTML);//②Set or get all internal nodes HTML code
                console.log(div1.innerText);//③Set or get all text inside the node
                
                console.log(window.getComputedStyle(div1,null));//View all properties (not IE Properties)
                console.log(div1.currentStyle);//View all properties( IE Properties)
                
            }
            function getById(){
                //Get the style attribute node of the element node
                var div1 = document.getElementById("div1").style;//obtain
                div1.backgroundColor = "#FF00FF";//Row level style sheet weight 1000;All node attributes, same hump nomenclature
                
                //Get to element node
                var divDoc = document.getElementById("div1");//obtain
                divDoc.innerHTML = "<s>king_land</s>";//Reset changes div In HTML code
            }
            
            //-------Dividing line——————————————————
            
            function getByName(){//adopt Name Get an array containing 1 or more nodes;
                
                var div = document.getElementsByName("div1");
                
                console.log(div.length);
                
                //Usage: get each node through the loop. The number of cycles starts from 0,<array.length
                for(var n = 0 ;n < div.length ; n++){
                    div[n].style.backgroundColor = "#FFFF00";
                }
                
                //div1.backgroundColor = "#FFFF00";
                //div[0].style.backgroundColor = "#FFFF00";//★
                
            }
            
            //-------Dividing line——————————————————
            
            //document.getElementsByTagName();//Same as Name

            function getByTagName(){
                
                var div = document.getElementsByTagName("div");
                
                div[0].style.backgroundColor = "#00FF00";
                
            }
            
            //-------Dividing line——————————————————
            
            //document.getElementsByClassName();//Same as Name

            function getByClass(){
                
                var div = document.getElementsByClassName("div1");
                
                div[0].style.backgroundColor = "#00FFFF";
                
            }
            //-------Dividing line——————————————————
            
            function getAttr () {
                
                var img1 = document.getElementById("img1");
                alert(img1.getAttribute("src"));
                
            }//View attribute node getAttribute("Property name");
            
            //-------Dividing line——————————————————
            
            function setAttr () {
                
                var img1 = document.getElementById("img1");
                img1.setAttribute("src","../../2-CSS Basic grammar/img/bg_flower_multi.gif");
                img1.setAttribute("style","width: 100px;height: 100px;");
                
            }//Set attribute node getAttribute("Property name","Property value");
            
            //-------Dividing line——————————————————
            
            //JS Modify style summary
            //1,.className: Set a new class Name for example: div1.className = "div2";
            //2,.style: Set a new style for the element, for example: div1.style.background-color = "blue";
            //3,.style.cssText: To modify multiple styles for an element at the same time, for example: div1.style.cssText = "width:100px;height:200px;";
            

            
            
            
        </script>
        
        <style type="text/css">
            
            .div1{
                height: 100px;
                width: 100px;
                background-color: #000000;
                color: #FFFFFF;
                line-height: 100px;
                text-align: center;
            }
            
        </style>
        
        
    </head>
    <body>
        
        <div id="div1" name="div1" class="div1">
            //This is the test area
        </div>
        <div id="div1" name="div1" class="div1">
            //This is the test area
        </div>
        <div id="div1" name="div1" class="div1">
            //This is the test area
        </div>
        <img src="../../2-CSS Basic grammar/img/bg_flower_multi.gif" id="img1"/>
        
        
        <br />
        <button onclick="getById()">adopt ID modify divcolor</button>
        <br />
        <button onclick="getByName()">adopt Name modify divcolor</button>
        <br />
        <button onclick="getByTagName()">adopt TagName modify divcolor</button>
        <br />
        <button onclick="getByClass()">adopt ClassName modify divcolor</button>
        <br />
        <button onclick="getAttr()">Take to img Of src Property value</button>
        <br />
        <button onclick="setAttr()">modify img Of src Property value</button>
        
    </body>
</html>

2.2 common operations of hierarchical nodes

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        
        <script type="text/javascript">
            
                window.onload = function (){
                    
                    //Get common attributes of hierarchy node
                    
                    var ul1 = document.getElementById("ul1");
                    
//                    var lis = ul1.getElementsByTagName("li");  //Only get all li in ul1
//                    var lis = document.getElementsByTagName("li");  //Get all li in the page

                    console.log(ul1.childNodes);//Get all child nodes of an element (including element nodes, text nodes)
                    
                    console.log(ul1.firstChild);//Get the first child of the element
                    
                    console.log(ul1.lastChild);//Get the last child of the element
                    
                    console.log(ul1.ownerDocument);//Get the root node of the current document at html In the document document node
                    
                    console.log(ul1.parentNode);//Get the parent of the current node
                    
                    console.log(ul1.previousSibling);//Get the previous sibling of the current node
                    
                    console.log(ul1.nextSibling);//Get the next sibling of the current node
                    
                    //All the above attributes will get all the element nodes and text nodes. If only the element nodes are needed, the corresponding Element Properties, such as: firstChild→firstElementChild
                    
                    console.log(ul1.attributes);//Get all attribute nodes of the current node
                    
                }
                
                //-------Create and add nodes——————————————————
                    
                //Method 1:.creatElement("Tag name")To create a new node, you need to cooperate with setAttribute()Method to set properties;
                //Method 2:.appendChild(Node name)Append a new node at the end of the element
                //Method 3:.insertBefore(New section roll call,Target node name): Insert new node before target node
                //Method 4: clone the object.cloneNode(true/false): The clone node can be called by whoever needs to clone; the pass parameter can be true/false,true Represents clone current node and child node; false Indicates that only the current node is cloned, not the child node.
                    
                function appendImg(){
                    
                    //1,Create a picture node
                    var img = document.createElement("img");
                    //2,to img Node settings properties
                    img.setAttribute("src","../../1-HTML Basic label/ivicon.png");
                    //3,Will be set up img Node append to body last
                    document.body.appendChild(img)//.setAttribute("src","../../img/2017-02-25_143342.png");
                    
                }
                
                function insertImg(){
                    
                    //1,Create a picture node
                    var img = document.createElement("img");
                    //2,to img Node settings properties
                    img.setAttribute("src","../../1-HTML Basic label/ivicon.png");
                    //3,In two ul Insert picture between
                    var ul2 = document.getElementById("ul2");
                    document.body.insertBefore(img,ul2);
                    
                }
                var count = 2;
                function copyUl(){
                    
                    //1,Take to ul2 node
                    var ul2 = document.getElementById("ul2");
                    //2,Clone node
                    var ul2Clon = ul2.cloneNode(true);
                    count ++;
                    ul2Clon.setAttribute("id","ul"+count)
                    //3,In the original ul2 Insert new clone node before node
                    document.body.insertBefore(ul2Clon,ul2);
                    
                }
                
                //-------Delete and replace nodes——————————————————
                
                //1,.removeChild(Node to be deleted): Delete the specified node from the parent container;
                //2,.replaceChild(New node, replaced node): Replace the specified node with a new node. If the new node is an existing node in the page, it will be deleted and replaced with the specified node.
                
                function deleteUl1(){
                    
                    //Take to ul1
                    var ul1 = document.getElementById("ul1");
                    if (ul1){
                        //From parent container body Delete from ul1 node
                        document.body.removeChild(ul1);
                    }else{
                        alert("It's long gone");
                    }
                    
                }
                
                function ul1ReplaceUl2(){
                    
                    var div = document.createElement("div");
                    div.setAttribute("style","width: 100px;height: 100px;background-color: #20B2AA;");
                    var ul2 = document.getElementById("ul2");
                    document.body.replaceChild(div,ul2);
                    
                }
                
        </script>
        
        <style type="text/css">
            
            ul{
                width: 600px;
                list-style: none;
                padding: 0;
                background-color: #20B2AA;
                display: flex;
                justify-content: space-around;
                margin-top: 20px;
            }
        
        </style>
        
    </head>
    <body>
        
        <ul id="ul1">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
        
        <ul id="ul2">
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
            <li>Item 4</li>
        </ul>
        
        <button onclick="appendImg()">Insert a picture at the end</button>
        <button onclick="insertImg()">In two ul Insert a picture between</button>
        <button onclick="copyUl()">copy One ul2</button>
        <br />
        
        <button onclick="deleteUl1()">delete ul1</button>
        <button onclick="ul1ReplaceUl2() ">use ul1 replace ul2</button>
        
        
        
        
    </body>
</html>

2.3 table operation

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>DOM Operation table</title>
        
        <script type="text/javascript">
            
            //Table object:
            //1,rows Attribute: returns all rows and arrays in the table;
            //2,insertRow(index): In table No index+1 Row, insert a new row;
            //3,deleteRow(index): Delete the index+1 that 's ok;
            
            //Table row object:
            //1,cells Property: returns all cells and arrays in the current row;
            //2,rowIndex Property: returns the index order of the current row in the table, starting from 0;
            //3,insertCell(index): On the current line index+1 Insert a td;
            //4,deleteCell(index): Delete the index+1 individual td;
            
            //Cell object for table:
            //1,cellIndex Property: returns the index order of cells in this row, starting from 0;
            //2,innerHTML Property: set or return the HTMl code;
            //3,align(valign)Property: sets the horizontal alignment of the current cell;
            //4,className Properties: setting cell's class name.
            
            function newRow(){
                
                var book = prompt("title:");
                var price = prompt("Price:");
                
                var table = document.getElementsByTagName("table");
                //Insert a new row in the last row of the table
                var newRow = table[0].insertRow(table[0].rows.length-1);
                //Set cells for new rows
                var cell0 = newRow.insertCell(0);
                cell0.innerHTML = book;
                var cell1 = newRow.insertCell(1);
                cell1.innerHTML = price;
                
                getSum();
                
            }
            
            function deleteRow(){
                
                var table = document.getElementsByTagName("table");
                if(table[0].rows.length>2){
                    table[0].deleteRow(table[0].rows.length-2);
                }else{
                    alert("Delete delete delete! Delete your sister!")
                }
                getSum();
            }
            
            function changeTitle(){
                
                var color = prompt("Please enter a 6-digit hex color value:");
                var table = document.getElementsByTagName("table");
                table[0].rows[0].style = "background-color:#"+color;
                
            }
            
            function copyRow(){
                
                var table = document.getElementsByTagName("table");
                var copyRow = table[0].rows[table[0].rows.length-2].cloneNode(true);
                var heJi = table[0].rows[table[0].rows.length-1];
                //Because of the browser, the<tr>Wrapped in<tbody>in
                //therefore<tr>Not really<table>The child node of the<table>In<tbody>Insert;
                
                if(table[0].rows.length>2){
                    table[0].getElementsByTagName("tbody")[0].insertBefore(copyRow,heJi);
                }else{
                    alert("No rows to copy");
                }
                getSum();
            }
            
            function getSum(){
                //Get all rows of the current table table
                var table = document.getElementsByTagName("table");
                var rows = table[0].rows;
                //
                if(rows.length<=2){
                    rows[rows.length-1].cells[1].innerText = 0 + "element";
                    alert("There are no rows to calculate!");
                    return;
                }
                //Summation
                var sum = 0 ;
                
                for(var i = 1 ; i <= rows.length-2 ; i++){//Line 0 and last line discard 1  rows.length-2
                    
                    var cells = rows[i].cells;//Get cell
                    sum += parseFloat(cells[cells.length-1].innerText);//Contents of last cell( innerText) Convert to numbers and sum!
                    
                }
                
                rows[rows.length-1].cells[cells.length-1].innerText = sum.toFixed(2) + "element";
                
            }
            
            window.onload = function(){
                getSum();
            }
            
            
        </script>
        
        <style type="text/css">
            
            table{
                border-collapse: collapse;
                width: 400px;
                text-align: center;
                color: #585858;
            }
            td,th{
                border: 1px solid #8B8A8B;
            }
            table tr:last-child{
                color: #E70014;
            }
            
        </style>
        
    </head>
    <body>
        
        
        <table>
            <tr>
                <th>title</th>
                <th>Price</th>
            </tr>
            <tr>
                <td>A room with a view</td>
                <td>30.00 element</td>
            </tr>
            <tr>
                <td>Happiness comes from the sky</td>
                <td>18.50 element</td>
            </tr>
            <tr>
                <td>60 An instant</td>
                <td>32.00 element</td>
            </tr>
            <tr>
                <td>total</td>
                <td></td>
            </tr>
        </table>
        
        <br />
        
        <button onclick="newRow()">Add a line</button>
        <button onclick="deleteRow()">Delete last line</button>
        <button onclick="changeTitle()">Change Title Style</button>
        <button onclick="copyRow()">Copy last line</button>
        

    </body>
</html>

3, Mouse and keyboard, things that have to be said -- events in JS

1. Tripartite confrontation -- event classification in JS

1.1 mouse events

Click click

dblclick double click

mouseover mouse in

mouseout mouse out

mousemove mouse over

mousedown mouse down

mouseup mouse up

1.2 keyboard events

keydown: triggered when the keyboard is pressed

keypress: momentary trigger when the keyboard is pressed and released

keyup: triggered when the keyboard is raised

[precautions]
① Execution order: keydown keypress keyup
② Long term and on time, the keydown keypress will be executed repeatedly
③ There is a keydown event, not necessarily a keyup event (there may be no keyup when the mouse is moved during event triggering)
④ keypress event can only capture letters, numbers, symbols (including carriage returns and spaces), not function keys; keydown keyup can basically capture all function keys, with special exceptions
⑤ keypress is case sensitive, keydown keyup is not;
⑥ keypress does not distinguish between the main keyboard and the keypad, and keydown keyup does;
[how to determine the keyboard trigger key]
(1) trigger parameter e in trigger function represents key event;
(2) confirm the Ascii code value of the case through e.keyCode, and then confirm the key;
(3) compatible with all browsers (generally unnecessary):
Var evn = e|event; / / get the key
 var code = evn.keyCode Wei evn.which Wei evn.charCode ; / / get the key code

1.3 HTML events

2. One shore and the other -- event model in JS

2.1 DOM0 event model

2.1.1 inline model: directly use function name as attribute value of an event attribute of HTML tag;
Chestnut < button ο nclick = "func()" > < button >
Disadvantage: it violates the W3C's basic principle of separating HTML from JS!

 

2.1.2 script model: binding through event attribute in JS script;
Chestnut window.onload = function(){}
Limitation: only one event of the same type can be bound to the same node;

 

2.2 DOM2 event model (Chestnuts behind it!)

Advantages: multiple listeners of the same type of events can be added to the same node;


① Add event binding:
Before IE10: btn1.attachEvent("onclick", function);
Other browsers: btn1.addEventListener("click", function, true/false);
true: indicates event capture; false (default): indicates event bubbling
Compatible writing: if(btn1.attackEvent){btn1.attachEvent("onclick", function);} else{btn1.addEventListener("click", function, true/false);}

② Unbind event:
. detachEvent("onclick", function name);
. removeEventListener("click", function name);
Note: if the time ceiling is cancelled, the callback function must use a named function instead of an anonymous function. When canceling the event topping, you need to pass in the function name;

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Here are chestnuts</title>
        
        <script type="text/javascript">
            window.onload = function (){
                
                var btn1 = document.getElementById("btn1");
                function func1(){
                    alert(1);
                }
                function func2(){
                    alert(2);
                }
                btn1.addEventListener("click",func1,false);
                btn1.addEventListener("click",func2,false);
                
                var btn2 = document.getElementById("btn2");
                btn2.addEventListener("click",function(){
                    btn1.removeEventListener("click",func1);
                },false);
                
            }
        </script>
    </head>
    <body>
        
        <button id="btn1">I'll pop up the window!</button>
        
        <br /><br />
        
        <button id="btn2">Point I don't pop the window!</button>
    </body>
</html>

3. Up, down -- event flow in JS

3.1 event bubbling

When a DOM element triggers an event, it will trigger the events of the same type of its ancestor element one by one from the current DOM element until the DOM root node;
DOM0 event flow is event bubbling;
The. attachEvent() event is used in IE, which is bubbling;
Events added by other browsers. addEventListener() are bubbling when the third parameter is false.

3.2 event capture

When a DOM element triggers an event, events of the same type of its ancestor elements will be triggered one by one from the DOM root node until the current DOM element is triggered;

Only events added with. addEventListener() are captured when the third parameter is true.

3.3 prevent incident bubbling

IE browser: set the e.cancelBubble property to true;
Other browsers: call e.stopPropagation(); method

3.4 cancel event default behavior

IE browser: set the e.returnValue property to false;
Other browsers: call e.preventDefault(); method

(here are chestnuts)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Event flow</title>
        <style type="text/css">
            
            #div1{
                width: 200px;
                height: 200px;
                background-color: #20B2AA;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            #div2{
                width: 100px;
                height: 100px;
                background-color: #436690;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            #div3{
                width: 50px;
                height: 50px;
                background-color: #4E2E83;
                color: #FFFFFF;
                font-size: 20px;
                font-weight: 700;
            }
            
        </style>
        
    </head>
    <body>
        <div id="div1">
            <div id="div2">
                <div id="div3">3</div>
                2
            </div>
            1
        </div>

        <a href="../07 JS In DOM/note.html" onclick="stopHref()">Jump page</a>
    </body>
    
    <script type="text/javascript">
        var div1 = document.getElementById("div1");
        var div2 = document.getElementById("div2");
        var div3 = document.getElementById("div3");
        
        div1.addEventListener("click",function(e){
            handleE();
            console.log("div1 Triggered click event");
        },false);
        
        div2.addEventListener("click",function(e){
            handleE();
            console.log("div2 Triggered click event");
        },false);
        
        div3.addEventListener("click",function(e){
            handleE();
            console.log("div3 Triggered click event");
        },false);

        function handleE(e){
            var evn = e||window.event;
            evn.stopPropagation();    
        }
        function stopHref(e){
            
            e = e||window.event;
            if (e.preventDefault) {
                e.preventDefault(); //IE outside 
            } else {
                e.returnValue = false; //IE     
            }

            alert("How angry!");
            
        }
        
    </script>
    
</html>

  

 

Posted by phpforever on Mon, 22 Jun 2020 19:58:00 -0700