JavaWEB notes 11 node cases and JSON objects in JavaScript

JavaWEB notes 11 node cases and JSON objects in JavaScript

I Find / get elements through node relationships:

In addition to the common methods of obtaining tag elements such as id name, class name and tag type, the methods of obtaining tag elements in JS can also find and obtain elements through node relationship. The following will introduce the corresponding common methods of finding and obtaining elements through node relationship:

  • Get all nodes in the document:
var nodeARR = document.all;	
//All attribute can get all node objects
for(var i=0;i<nodeARR.length;i++){ alert(nodeARR[i]); }
  • Get all the child nodes under the label:
var all = document.body.childNodes;
  • Get different types of child nodes under the label:
firstChild Get the current first child node
lastChild  Get the current last child node
  • Gets the parent node of the current element: parentNode
  • Get the sibling node of the current node:
nextSibling  Get the next node of the current node: sibling node
previousSibling  Get the previous node of the current node: sibling node
  • The above methods for obtaining nodes can be concatenated and called many times, because the results are the corresponding nodes
  • Get node elements, including label, text and attribute
  • Get node value of text node: nodeValue
    Node type: nodeType
    Node name: nodeName
  • Get the attributes of the element: (empty text and comments are ignored, which is more common)
parentElement          Gets the parent element object of the current element
firstElementChild      Gets the first label object of the current parent element
lastElementChild       Gets the last label object of the parent element
previousElementSibling Gets the last sibling element object
nextElementSibling     Gets the next sibling element object

II Calculator case:

Realize a simple network calculator through JS:

First, you need to create an input field and a table in the html tag. The consolidated attribute in the table is colspan="2". The idea of establishing a calculator is as follows:
[1] First realize simple operations: point a number, point an operator, then point a number, and finally point the equal sign to display the results

  • 1) All numbers and decimal points fall into one category and add class
  • 2) Put all operators into one class and add class
  • 3) Add id separately for other keys
  • 4) Implementation of Digital: document Getelementsbyclass ("numeric class"); And bind click events
  • 5) Simple operation implementation: three variables are required to store: the first number operator and the second number
  • 6) Click to store the innerText of the first object
  • 7) Bind click event to operator: clear the display box when clicking operator: give the first number to the second number and clear the first number to take the next input number
  • 8) Calculation function: convert the array of strings into numbers: Number(numValue)
  • 9) Return to zero: Click to display 0 and clear the number 1, number 2 and operator

[2] Realize four operations: main idea: use the value transfer between the corresponding two parameters
Full code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Web calculator</title>
    <style type="text/css">
        input {
            height: 50px;
            width: 400px;
            font-size: 30px;
        }
        tr {
            text-align: center;
            font-size: 25px;
        }
        td:hover {
            background-color: aquamarine;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <center>
        <input type="text" name="" value="0" disabled="disabled" id="showResult" />
    </center>
    <table border="1" align="center" cellspacing="0" cellpadding="0" height="500px" width="400px">
        <tr>
            <td id="clear">C</td>
            <td id="del">Backspace</td>
           <td id="pcnt">%</td>
         <td class="opr">/</td>
        </tr>
        <tr>
             <td class="num">7</td>
            <td class="num">8</td>
            <td class="num">9</td>
            <td class="opr">*</td>
        </tr>
        <tr>
            <td class="num">4</td>
            <td class="num">5</td>
            <td class="num">6</td>
            <td class="opr">-</td>
        </tr>
        <tr>
            <td class="num">1</td>
            <td class="num">2</td>
            <td class="num">3</td>
            <td class="opr">+</td>
        </tr>
        <tr>
            <td colspan="2" class="num">0</td>
            <td class="num">.</td>
            <td id="result">=</td>
        </tr>
    </table>
</body>
<script type="text/javascript">
    var num1='';
    var num2='';
    var middle_ysf='';
    var flag = 1; //Record whether the equal sign is clicked
    var flag2 = 1; //Record whether the operator has been clicked once before clicking
    var flag3 = 1; //Record whether to restart the calculation based on the existing calculation results
    var show_result = document.getElementById('showResult');
    var nums_value = document.getElementsByClassName('num');
    for(let i=0;i<nums_value.length;i++) {
        nums_value[i].onclick = function () {
            flag = 1;
            flag3 = 0;
            var text = this.innerText;
            if(num1==='' && text === '0'){
                show_result.value = 0;
            }else{
                num1 += text;
                show_result.value = num1;
            }
    };
    var ysf = document.getElementsByClassName('opr');
    for(let i=0;i<ysf.length;i++){
        flag2 = 0;
        ysf[i].onclick=function () {
            if(num2 === ''){
                num2 = num1;
                num1='';
            }
            else if(!flag3 && num2){
                num2 = num1;
                num1='';
            }
            else if(flag){
                flag3 = 1;
                calculate();
                //Flag is used as the click flag. When calculating after clicking, it only needs to be calculated when clicking the equal sign
                //Skip the calculation here. After recording the operator, get num1 and click the equal sign before the final calculation
            }
            else if(!flag2){
                flag3 = 1;
                calculate();
                //During continuous calculation of flag2, the corresponding value will be displayed and calculated
            }
            middle_ysf = this.innerText;
        }
    }
    document.getElementById('result').onclick = function () {
        flag = 0;
        calculate();
        flag2 = 1;
        flag3 = 1;
        middle_ysf = '';
    };
    function calculate() {
            var templatevalue = null;
            num1 = Number(num1);
            num2 = Number(num2);
            switch (middle_ysf) {
                case '+': {
                    templatevalue = num2 + num1;
                    break;
                }
                case '-': {
                    templatevalue = num2 - num1;
                    break;
                }
                case '*': {
                    templatevalue = num2 * num1;
                    break;
                }
                case '/': {
                    if (num2 === 0) {
                        alert("Illegal operation: divisor cannot be 0!");
                        num1 = '';
                        num2 = '';
                        ysf = '';
                        templatevalue = 0;
                    } else {
                        templatevalue = num2 / num1;
                    }
                    break;
                }
            }
            num2 = templatevalue;
            num1 = '';
            if(!flag || !flag2) {
                show_result.value = num2;
            }
        }
    }
    document.getElementById("clear").onclick = function () {
        num1 = '';
        num2 = '';
        ysf = '';
        show_result.value = 0;
    };
    document.getElementById('del').onclick = function () {
        if(num1.length>1){
            num1=num1.substring(0,num1.length-1);
            showResult.value=num1;
        }
        else if(!(num1.length-1)){
            showResult.value=0;
            num1='';
        }
    };
    document.getElementById('pcnt').onclick = function () {
        var val = show_result.value;
        var s = val*100+'%';
        show_result.value = s;
    };
</script>
</html>

(there are still problems with the above code, which does not deal with the digital accuracy of JS)

III this question:

This represents the reference of an object in JAVA. Whoever calls the method, this in the method represents who. The common uses of this in JS are as follows:

  • 1) this represents the window object in the JS global scope
  • 2) this in the function also represents the window object by default
  • 3) this in the event handler function represents the element that binds the event

IV JSON object:

1. Introduction to JSON object:

  • JAVA takes classes to encapsulate the corresponding data, but there is no concept of classes in JS
  • JS can encapsulate data in functions, that is, define functions as constructors, mainly parametric structures
  • When calling, new an object and pass in the corresponding parameters to make it conform to the construction rules in parametric construction
  • JSON is the main mode used by JS to encapsulate data
  • JSON is a data exchange format. JSON uses a text format completely independent of the programming language to store and represent data. A clear hierarchical structure is conducive to people's understanding and analysis, and can also improve the efficiency of network information transmission

2.JSON object:

  • JSON is used to encapsulate scattered data. Syntax format: {key ":" value "} note: key values are separated by colons, and multiple key value pairs are separated by commas. Where key is of string type and value is of any type. For example, JSON object:
var person = {"name":'Zhang San',"age":24,"arr":[0,10,20],"funct":function(){}};
  • Press key to find value in JSON object:
    1) Most commonly used: object name Key name and JSON can be nested at multiple levels, that is, the value corresponding to the key is also a JSON object, so the call can be used Make level call
    2) The format of object ['key name'] is called accordingly
  • Operation of attributes in JSON:
    Add a property: JSON object name Key name = value assigned to the key
    Delete a property: delete JSON object name Key name
  • In JS, it is different to distinguish between JSON objects and strings conforming to JSON format. Strings conforming to JSON format are actually strings. Strings conforming to JSON format can be converted into JSON objects. Use the corresponding method:
var JSON object = JSON.parse(character string)
  • Convert JSON objects into corresponding strings conforming to JSON format:
var str = JSON.stringify(JSON object);
  • Note that when converting a string to JSON, you must use a compact format (that is, the representation of key value pairs in one line). The beautified string conversion will contain newline characters, so the conversion will fail
  • The format in the string is enclosed by '', and the key in it will not be converted successfully when '' is used. Because the format of JSON object is very strict, it must be cited with '' and '' as keys

3.JSON array and JSON traversal:

  • JSONarr is in the form of an array. When storing data, the array elements stored in the array are JSON objects
  • JSON traversal: the for in loop can traverse JSON objects in a simple way:
for(key in p){ alert(p[key]); }
  • The traversal of the for in array in JS is the same as that in JAVA: for(index in arr) {}
  • Therefore, the following format can be used when traversing JSONARR:
for(index in JSONarr){
	var JSONOBJ = JSONARR[index];
	for(key in JSONOBJ){
		alert(JSONOBJ[key]);
	}
}
  • The JSON string in JAVA needs to be escaped: str="{\name \": \ "Zhang San \", \ "age\":100}“

V call method:

The call method in JS refers to using call() in the function object to call the function. One of the main functions of the call method is to change the this point in the function. In JS, call(), apply(), bind() can be used to call the function

Vi Carousel case:

effect:

code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			/* Observation hole */
			#show {
				width: 230px;
				height: 320px;
				border: 1px black solid;
				/* Child overflow parent hidden */
				overflow: hidden;
				transition: margin-left 0.5s;
			}

			#content {
				width: 920px;
				height: 320px;
				/* margin-left: -460px; */
				transition: margin-left 0.5s;
			}

			#d1 {
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_01.png);
				float: left;
			}

			#d2 {
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_02.png);
				float: left;
			}

			#d3 {
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_03.png);
				float: left;
			}

			#d4 {
				width: 230px;
				height: 320px;
				background-image: url(img/main02_centent_04.png);
				float: left;
			}
			
			#dots {
				position: absolute;
				width: 230px;
				margin-top: 300px;
				margin-left: auto;
				/* border: 1px black solid; */
				display: flex;
				justify-content:center;
			}
			
			.dot {
				width: 14px;
				height: 14px;
				border: 1px black solid;
				border-radius: 7px;
				float: left;
				margin-left: 10px;
				font-size: 10px;
				color: white;
				background: grey;
				text-align: center;
			}
		</style>
	</head>
	<body>
		<div id="show" onmouseover="stop()" onmouseout="start()">
			<!-- indicator -->
			<div id="dots">
				<div id="dot1" class="dot">1</div>
				<div id="dot2" class="dot">2</div>
				<div id="dot3" class="dot">3</div>
				<div id="dot4" class="dot">4</div>
			</div>
			<div id="content">
				<div id="d1">

				</div>
				<div id="d2">

				</div>
				<div id="d3">

				</div>
				<div id="d4">

				</div>
			</div>
		</div>
		<script type="text/javascript">
			var box = document.getElementById("show");
			var content = document.getElementById("content");
			
			var dots = document.getElementsByClassName('dot')
			//First set the first point to red
			dots[0].style.background='red';

			var count = 0;
		
			function scorll() {
				count++;
				if (count == 4) {
					count = 0;
				}
				//Clear only the set background color
				//When the picture scrolls, all points are restored to the default gray
				clearColor();
				dots[count].style.background='red';
				content.style.marginLeft = (-1 * count * 230) + "px"; //-230  -460  -690
			}

			var tiemID=setInterval(scorll, 2000);

			//Move the mouse over to stop the rotation
			function stop() {
				clearInterval(tiemID);
			}
			//Move the mouse out to start the rotation
			function start() {
				 tiemID=setInterval(scorll, 2000);
			}
			
			//Set the color of small dots as the default color
			function clearColor(){
				for (var i=0;i<dots.length;i++) {
					dots[i].style.background='grey';
				}
			}
			//Operation: click the corresponding indicator to jump to the corresponding picture
		</script>
	</body>
</html>

Keywords: Javascript

Added by refined on Sat, 25 Dec 2021 22:17:05 +0200