Javascript statement(下)

Javascript statement(下)


一、ECMA基本对象

typeof() // Only can judge the type of the obj in simple
obj_1 instanceof type_of_obj // Return the boolean

1. ECMA对象概述

原始对象(0bject)

  • 其他所有对象都是继承于原始对象

11种内置对象

/*
Array, String, Date, Math
Boolean, Number, Function
Global, Error, RegExp, Object
*/

// 实例化对象 (s == s1)
var s = "hello"
var s1 = new String("hello")

2. Function 对象

the name of functions and variables can't be same, because they only are the vessel to store the memory address. If the name of functions and variables are same, the memory address will be covered

// method one
function func_1(args){
	statement;
	return value
}
var ret=func1()

// method two
var func2 = new Function(arg1, rag2, "statement")
func2(args)

// method three (anonymous function)
var func3=function(){
	statement;
	return value
}

// These atrribute and means of function
function.length		// Return the args' number of the function object
void()				// Ban the function to return value
Tostring()			// 
Valueof()			// 

// The function will automatically be performed
(function (arg){
	statement;
})("123")

3. Arguments对象

Can directly tansfer arguments in the function of js without setting arguments in advance
Arguments are a ordered array

var ret = 0;
function add(){
	console.log(arguments.length);
	console.log(arguments);
	
	for (var i in arguments){
		ret+=arguments[i]
	}
	return ret;
}
alert(add(1,2,3,4))
}

4. String对象

属性

var s = "hello"
s.length

for (var i in s){
	console.log(s[i])
}

方法

// the style of font
s.italics()
s.bold()
s.ancho()

// Switch to big or small alphabet
s.toUpperCase()
s.toLowCase()

// Get the character designated
s.charAt()		// get the character designated the position
s.charCodeAt()	// get the position of ASSIC by the character designated

// Search the characters
s.search()
s.match()
s.indexof()
s.lastindexof()

// replace, split and concat
s.replace(old,new_);	// Replace the string
s.split();				// To split the string by the character designated,then return a array
s.concat();				// To emerge the strings

// To truncate the string by a range
s.substr(start, length)
s.substring(start, end)
s.slice(start, end)			// The number of end can be minus

5. Array对象

When use the method of generating the array object to create a array, the number designate the length of the array newly created, but not the realistic value if only put one number into the list of arguments. and the length designated can not limit the length of array.

创建

var arr=[1,2,3,4];
var arr=new Array(1,2,3,4);

var ret = arr[1]	// 2

数组对象的方法

栈:先进后出(相当于一端开口的瓶子)
队列:先进先出(相当于两端开头的管道)

arr.join();		// All strings in the array will be emerge into a string

arr.push();		// Put the value into the array(bottle) one by one
arr.pop();		// Get the value from the top of array(bottle)

arr.unshift();	// Put the value into the bottom of array(bottle)
arr.shift();		// Get the value from the bottom of array(bottle)

arr.reverse();		// Make all value in the arry reverse the position
arr.sort();			// Defaultly, the values in the array are sorted by their order of first character in the asci table. But we can put the function defined by us into the list of arguments
// For example
function mysort(a,b){
	if(a>b){
		return 1;
	}else if(a<b){
		return -1;
	}else{
		return 0;
	}
}
arr.sort(mysort)

arr.concat()		// All strings in the array will be emerge into a string and it not change the former the array

数组对象的特性

  • JS数组可装任意类型,无限制;java等需提前规定数组所装的数据类型
  • JS数组长度没有限制

6. Date对象

创建方式

var date_obj=new Date();
var date_obj=new Date(5000);		// ms
var date_obj=new Date("2021/4/20 12:05:22")
alert(date_obj.toLocalString());
alert(date_obj.UTCString());

对象方法

var date_obj=new Date("2021/4/20 12:05:22")
date_obj.getFullYear();
date_obj.setMonth();
date_obj.getTimezoneOffset();	// return a number of minitue, which equate the local time minus the UTC time

7. 正则对象

RegExp molds:
i: Will let the big alphabet and small alphabet see as a same character
g: Everywhere can be used

var re_obj= /re_rule/g;
var re_obj= new RegExp("re_rule", "mold")	// mold need to be between [i, g];

alert(re_obj.test(str))		// Be used to test if the string can be matched. return the boolen

8. Math对象

Math.random()
Math.round()	// Get the int by that the fore number of decimal point add one if the next number of decimal point beyond 4
Math.pow()		// Return a result of the type's number, like 2**4

9. History对象

// Attribution
history.go()	// Arg: [0,-1,1]
history.forward()
history.back()

// Method
history.length

10. Location对象

location.reload()
location.href="url"

二、BOM对象

Let the js can interact with browser
常用方法

alert();

var ret = confirm();		// Pop up a frame that can use to interact, which have two options: confirm or cancel
var ret = prompt();		// Pop up a frame that can use to input

var timer_id = setInterval(func, gap);		// Set a timer to execute a function every certain time and  return the id of the timer
var timeout_id = setTimeout(func, gap);		// Set a timeout to execute a function after certain time
clearTimeout(timeout_id);					// Clear the timeout by the id

三、DOM对象

1. 自身属性

image

2. 导航属性

image

3. DOM方法

var ele=document.getElementById();
var ele=document.getElementsByclassName();
var ele=document.getElementByTagName();
var ele=document.getElementByName();

4. DOM属性

var ele2=ele.firstChile;
var ele2=ele.lastChile;
var ele2=ele.parentNode;
var ele2=ele.childNodes;
var ele2=ele.nodeName;
var ele2=ele.nodeType;
var ele2=ele.nodeValue;
var ele2=ele.getinnerHTML;

// Recommended the method of use
var ele2=ele.firstElementChild;
var ele2=ele.lastElementChild;
var ele2=ele.children;
var ele2=ele.nextElementSibling;
var ele2=ele.previousElementSibling;

5. DOM Event

常用event事件

<p click="func()"></p>
<p ondblclick="func()"></p>
<p onfocus="func()"></p>		<!-- Trigger when got the focus -->
<p onblur="func()"></p>			<!-- Trigger when lost the focus -->
<select onchange="func()"></select>		<!-- Trigger when contents of the area were changed.Generally it is used with select tag-->
<p onkeydown="func()"></p>		<!-- Trigger when press any key -->
<p onkeypress="func()"></p>
<p onkeyup="func()"></p>
<p onload="func()"></p>			<!-- Trigger when all element are loaded -->

<p onmousedown="func()"></p>
<p onmousemove="func()"></p>
<p onmouseout="func()"></p>
<p onmouseover="func()"></p>
<p onmousedown="func()"></p>

<!-- Pop up a prompt dialog box when select some text -->
<input type="text" onselect="func()">
<textarea onselect="func()">

onsubmit事件

<!-- Must put the event of "onsubmit" on the form tag, if the function triggered return "false", form tag will can't post -->
<form id="form" onsubmit="return func()">

<form id="form" onsubmit="func1()">
<script>
	function func1(event){
		event.preventDefault();		// Ban the form tag to post data
		event.stopPropadation();	// Prevemt two events simutaneously trigger from the same area covered two events
	}
</script>

绑定对象的两种方式

<!-- method one -->
<p click="func()"></p>

<!-- method two -->
<script>
	var obj = document.getElementByClassName();
	obj.onclick=function(){
		statement;
	}
</script>

增删改查操作

// Append
var son=document.createElement(tag_name);
son.innerHTML="hello ppp";
son.innerText="";
ele.appendChild(son);

// Delete
var ele=document.getElementsByClassName();
var last_son=ele.lastElementChild;
ele.removeChild(last_son);

// Modify
ele.style.fontSize="30px";
ele.className;
ele.classList.add(class_name);
ele.classList.remove(class_name);

四、实例训练

1. 模态对话框

要点提示

  • css中z-index属性

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0px;
            padding: 0px;
        }
        .content{
            height: 800px;
            background-color: dodgerblue;
        }
        .notice{
            position: fixed;
            left: 50%;
            top: 50%;
            margin-top: -150px;
            margin-left: -150px;
            height: 300px;
            width: 300px;
            background-color: darkseagreen;
        }
        .ground{
            position: fixed;
            top: 0px;
            left: 0px;
            height: 800px;
            width: 100%;
            background-color: gray;
            opacity: 0.7;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
    <div class="content" onclick="demonstrate()">
        <input type="button" value="Show">
    </div>
    <div class="bottom hide">
        <div class="ground"></div>
        <div class="notice">
            <input type="button" value="Hide" onclick="notDemonstrate()">
        </div>
    </div>

    <script>
        function demonstrate(){
            var ele= document.getElementsByClassName("bottom")[0];
            // alert(ele)
            ele.classList.remove("hide");
        }
        function notDemonstrate(){
            var ele= document.getElementsByClassName("bottom")[0];
            // alert(ele)
            ele.classList.add("hide");
        }
    </script>

</body>
</html>

2. 省市二级联动

要点提示

<select onchange="func1(this)"></select>
<script>
    function func1(self){
        alert(self.options(self.selectedIndex)).innerHTML)
    }
    
    city.options.length=0;		// Delete all the options
</script>

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<select id="province" onchange="alter(this)">
    <option>please select province</option>
</select>
<select id="city">
    <option>please select city</option>
</select>
<script>
    data={"peking":["chaoyang","tiananmen"], "guangdong":["shenzheng","huizhou"], "sichuan":["chengdu","mianyang"]};
    var pro = document.getElementById("province");
    var city = document.getElementById("city");

    for (var i in data) {
        var pro_option = document.createElement("option");
        pro_option.innerHTML=i;
        pro.appendChild(pro_option);
    }
    function alter(self){
        var province_selected = self.options[self.selectedIndex].innerHTML;
        city.options.length = 0;

        for (var i = 0;i<data[province_selected].length;i++) {
            var city_option = document.createElement("option");
            city_option.innerHTML=data[province_selected][i];
            city.appendChild(city_option);
        }
    }

</script>
</body>
</html>

3. 左右内容移动

要点提示

options.selected		// Can return a boolean

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .transfer{
            display: inline-block;
        }
    </style>
</head>
<body>
<select multiple size="10" id="right">
    <option>option1</option>
    <option>option2</option>
    <option>option3</option>
    <option>option4</option>
    <option>option5</option>
</select>

<div class="transfer">
    <input type="button" value="--->" onclick="single_move(0)">
    <input type="button" value="===>" onclick="all_move(0)">
    <input type="button" value="<---" onclick="single_move(1)">
    <input type="button" value="<===" onclick="all_move(1)">
</div>

<select multiple size="10" id="left">
    <option>choice1</option>
    <option>choice2</option>
    <option>choice3</option>
</select>

<script>
    function single_move(flag){
        var right = document.getElementById("right");
        var left = document.getElementById("left");
        if (flag==0){
            var arr = [right,left];
        }else if(flag==1){
            var arr = [left,right];
        }
        var all_options = arr[0].options;
        // console.log(all_options);
        var temp_num = all_options.length;
        var choice = 0;
        for (var i=0;i<temp_num;i++){
            console.log(temp_num)
            // console.log(all_options)
            // console.log(all_options[i].selected);
            // console.log(all_options[i].selected)
            if (all_options[choice].selected==true){
                // console.log(all_options[i])
                var temporary = all_options[choice--];
                arr[0].removeChild(temporary);
                arr[1].appendChild(temporary);
            }
            choice += 1;
        }
    }
    function all_move(flag){
        var right = document.getElementById("right");
        var left = document.getElementById("left");
        if (flag==0){
            var arr = [right,left];
        }else if(flag==1){
            var arr = [left,right];
        }
        var all_options = arr[0].options;
        // console.log(all_options);
        var temp_num = all_options.length;
        for (var i=0;i<temp_num;i++){
            var temporary = all_options[0];
            arr[0].removeChild(temporary);
            arr[1].appendChild(temporary);
        }
    }
</script>
</body>
</html>
posted @ 2021-06-29 12:00  notesForKai  阅读(52)  评论(0编辑  收藏  举报