第二章 JavaScript总结(下)

js参考表

	                      变量的引用
	<script>
	    var n=10; m = 10;  //全局变量
	    function  a () {
	        var x = 10; //局部变量
	        b = 10;//全局变量
	    }
	</script>
	
	定义变量(弱类型var定义)
	var string = "hello";//字符串
	var int = 10;//数字
	var flag = true;//boolean
	var array = [1,2,3,4];//数组的三种定义方式
	var array1 = new Array("hello","like","tzy");
	var array2 = new Array();//new Array(长度)
	array2[0] = 10;
	array2[1] = 10;
	array2[2] = 10;
	
	二维数组向外层数组里面添加7个内层数组,每个内层数组为2个长度
	var arr = new Array();
	for(var i=0;i<arr.length;i++){
	//创建一个长度为2的数组,并添加到arr中
	var temparr = new Array(2);
	arr[i] = temparr;
	}
	arr[0][0] = "星期天";
	arr[0][1] = "sunday";
	
	var n = null;//空
	var r;//未定义后赋值
	r = 10;
	r = null;//将r值赋值为空清除之前r的值
	
	                   文件的输出
	<p id = pid>Hello</p>
	<script>
	document.write("<h1>标签h1</h1>")  //在script里可以输出h1标签样式(绝对不要在文档加载完成之后使用)
	document.getElementById("pid").innerHTML="你好"; //改变id为pid的标签里面的输出文本
	</script>
	document.write("<h1>标签h1</h1>"+"</br>")//</br>换行
	
	
	                                      js事件
	注:函数名不可以包括事件名称
	onClick             单机事件
	onMouseOver         鼠标经过事件
	onMouseOut          鼠标移出事件
	onChange            文本内容改变事件//select下拉框中在换选择option的时候value值改变
	onSelect            文本框悬案中事件
	onFocus             光标聚集事件
	onBlur              移开光标事件
	onLoad              网页加载事件
	onUnload            关闭网页事件
	onscroll            滚动条事件(x=event.clientX   y=event.clientY获取光标位置    screenX  screenY获取光标位置 pageX pageY)
	screenX:鼠标位置相对于用户屏幕水平偏移量,而screenY也就是垂直方向的,此时的参照点也就是原点是屏幕的左上角。
	
	clientX:跟screenX相比就是将参照点改成了浏览器内容区域的左上角,该参照点会随之滚动条的移动而移动。
	
	pageX:参照点也是浏览器内容区域的左上角,但它不会随着滚动条而变动
	
	![](https://images2018.cnblogs.com/blog/1235870/201808/1235870-20180823114018674-1699892938.png)
	
	使用句柄的方式添加监听
	//方法名不加()调用的是方法对象如 function demo(){}
	addEventListener("字符串形式的监听事件不加on:如click",demo||'demo()'||或者直接匿名function(){});
	removeEventListener("字符串形式的监听事件不加on:如click",demo||'demo()'||或者直接匿名function(){});
	
	
	
	                      异常处理
	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>异常处理</title>
	    <script>
	        function demo() {
	        //尝试抛出异常
	            try {
	                alert(str);//str为空
	            }catch(err){
	                alert(err);
	            }
	            }
	        demo();
	        function demo1(){
	            var e = document.getElementById("txt").value;
	            try{
	                if(e==""){
	                    throw "您没有输入文字";//自定义异常
	                }
	            }catch(err){
	                alert(err);
	            }
	
	        }
	    </script>
	</head>
	<body>
	<form>
	    <input type="text" id="txt">
	    <input type="button" onclick="demo1()" value="按钮">
	</form>
	</body>
	</html>
	
	                    各种语句 参考语句案例
	
	                        运算符
	算数运算符:+,-,*,/,%,++,--;(++在前先运算在赋值,++在后先赋值在运算)
	赋值运算符:+=,-=,=,*=,/=,%=;
	字符串操作:(+拼接字符串)
	比较运算符:==,===,!=,!==,>,<,>=,<=;("10"与10==也是true)(===需要类型也相同前面就是false)
	逻辑运算符:&&,||,!,
	条件运算符(三木运算符):x<10?"✔执行":"✖执行";
	
	                            JsDOM对象(其实就是用对象点方法)(参考dom使用)
	当网页被加载时,阅览器就会创建页面的文档对象模型(Docunment Object Model)
	可以改变HTML 元素,属性,css样式,事件
	
	使用ID 找到HTML元素:<p id="pid">hello</p>    var nv = document.getElementById("pid");
	使用标签 找到HTML元素:<p>hello</p>    var nv = document.getElementsByTagName("p")//这个会寻找到p标签,如果是多个p标签则选择第一个
	根据name 找到HTML元素:<p name="pn">hello</p>  document.getElementsByName("pn");
	修改元素内容:nv.innerHTML = "world";//修改标签内容(文本及文本域使用没有效果)
	
	<textarea id="txtResult" cols="40" rows="10" value="aaa"></textarea>
	document.getElementById("txtResult").value =“要修改成的值”;
	//通过这种方法可以修改文本域的内容(按钮及没有value值得标签使用没有效果)
	
	
	改变HTML属性:<a href="http://www.baidu.com" id="aid">hello</a>
	(换地址)    docunment.getElementById("aid").href="http://www.qq.com";
	结合jsDOM对象案例学习
	(修改图片的src属性可以换图片)
	(修改各种css样式)    docunment.getElementById("id").style.color="blue";
	
	
	
	                                    JsBom对象 参考Bom使用表
	window对象
	window.open("http://www.baidu.com","打开页面名字",
	"height=200,width=200,top=100,left=100,
	toolbar=no,menubar=no")打开页面(三个参数 1、url 2、htmlName 、3style)
	window.close();关闭页面
	
	Screen对象(适配)(包含用户有关的屏幕信息)
	document.write("可用高度"+screen.availHeight+"可用宽度"+screen.availWidth);
	document.write("高度"+screen.height+"宽度"+screen.width);
	
	Location对象(用于获取当前页面URL,并把阅览器重新定向到新的页面)
	window.location.hostname;返回web主机的域名
	location.pathname;返回当前页面的路径和文件名
	location.port;返回web端口
	location.href;返回当前页面的地址
	location.protocol;返回所使用的web协议
	location.assign()方法加载新的文档
	
	History对象(包含阅览器历史(URL)的集合)
	history.back()与在阅览器点击后退按钮相同
	history.forward()与在阅览器中点击按钮向前相同
	history.go()进入历史中的某个页面
	                                JsBom对象 参考Bom使用表
	<!DOCTYPE html>
	<html lang="en">
	<head>
	    <meta charset="UTF-8">
	    <title>JsDOM对象</title>
	    <script type="text/javascript" src="tzy.js"></script>
	</head>
	<body>
	<p name = "pn">hello</p>
	<p name = "pn">hello</p>
	<p name = "pn">hello</p>
	<p name = "pn">hello</p>
	<a id = "aid" title = "title属性"></a>
	<ul><li id="li1">1</li><li>2 3</li><li>3</li></ul>
	<div id="div">
	    <p id="pid">我是p节点</p>
	    <p id="pid1">我是p1节点</p>
	</div>
	<script>
	    function getName() {
	        var count = document.getElementsByName("pn");//根据name获取
	        alert("count长度"+count.length);//看是否获取到
	        var p = count[2];
	        p.innerHTML = "world";
	        var count1 = document.getElementsByTagName("p");//根据标签名获取
	        alert("count1长度"+count1.length);
	        var p1 = count1[3];
	        p1.innerHTML = "hahaha";
	    }
	    getName();
	    function getSetAttr() {
	        var a = document.getElementById("aid");//根据id获取
	        var attr = a.getAttribute("title");//获取当前元素某个属性值
	        alert(attr);
	        a.setAttribute("id","动态被设置为id")//设置当前元素某个属性值
	        var attr1 =a.getAttribute("id");
	        alert(attr1);
	    }
	    getSetAttr();
	function getChildNode(){
	    var childnode = document.getElementsByTagName("ul")[0].childNodes;//获取子节点项,注意ul里面空格也会算子节点,所以要去掉空格
	    alert("ul的字节点数"+childnode.length);
	    alert("ul里的第一个子节点类型"+childnode[0].nodeType);//返回都是1   因为在DOM中元素的nodetype为1  属性为2   文本为3  注释为8  文档为9
	    alert("ul里的第二个子节点类型"+childnode[1].nodeType);
	}
	getChildNode();
	function getParentNode() {
	    var li1 = document.getElementById("li1");
	    alert("li1的父节点"+li1.parentNode.nodeName);//获取父节点及名字
	}
	getParentNode();
	function createNode(){
	    var body = document.body;//获取body
	    var input = document.createElement("input");//创建节点
	    input.type = "button";
	    input.value = "自建按钮";
	    body.appendChild(input);//将节点添加到body中
	    //createTextNode()添加文本节点
	}
	    createNode();
	function addNode() {
	    var div = document.getElementById("div");
	    var node = document.getElementById("pid");
	    var newnode = document.createElement("p");
	    newnode.innerHTML = "这是我添加的p节点";
	    div.insertBefore(newnode,node);//添加节点到某个节点前
	}
	    addNode();
	function removeNode() {
	    var div = document.getElementById("div");
	    var p = div.removeChild(div.childNodes[2]);//删除p节点因为空格算一个节点
	}
	    removeNode();
	function getSize(){
	    //offsetheight     网页尺寸(不包含滚动条)
	    //scrollheight     网页尺寸(包含滚动条)
	    var height = document.body.offsetHeight||document.documentElement.offsetHeight;//兼容性写法
	    var width = document.body.offsetWidth;
	    alert("宽度"+width+"高度"+height);
	}
	    getSize();
	</script>
	</body>
	</html>
	previousSibling获取平级的上一个节点
	nextSibling获取平级的上一个节点
	
	
	
	
	
	                                        js对象
	创建对象方法
	people = new Object();//创建对象
	people.name = "张三";
	people.age = "15";
	document.write(people.name+people.age);
	people = {name:"张五",age:"30"};
	document.write(people.name+people.age);
	
	通过函数创建对象
	function people(name,age){
	this.name = name;
	this.age = age;
	}
	son = new people("张1",25);
	document.write(people.name+people.age);
	prototype可以给对象添加属性和方法
	
	                                              常用方法
	isNaN(input)//判断input是否是一个数字,不是数字则isNaN则返回true,它是一个内置的方法
	某类型.parseInt()//修改某类型为int类型(还可以parseFloat double等等)
	
	
	Math的一些方法
	Math.random()//随机数(从[0,1))可以*几增大
	Math.ceil()//向上取整
	Math.floor()//向下取整
	Math.round()//四舍五入
	Math.min()//最小值
	Math.max()//最大值
	Math.abs()//绝对值
	Math.pow(x,y)//返回x的y次幂;
	r.toFixed(2)//保留2位小数,r为double类型;
	
	String的一些方法
	String.replace('mmp','*')//寻找字符串mmp修改为*(更换)
	String.indexOf('mmp') == -1//寻找字符串有没有mmp,(有返回其位置)如果没有则返回-1;
	String.match('mmp')匹配mmp字符串 如果有打印mmp 如果没有返回null;
	String.toUpperCase和toLowerCase全部转换为大写和转换为小写
	arr = String.split(",")//用,各开装入数组;
	
	数组的一些方法
	arr1 = arr.concat(arr2);//arr数组合并arr2数组装入arr1里
	arr.reverse()//数组倒转;
	arr.push("qwe")//在数组末尾追加qwe元素
	arr.sort(mySort);// 数组排序  mySort为方法 注意没加()和引号的是方法的对象(也可以写成"mySort()")
	function mySort(a,b){
	   //return a-b;升序(默认)
	   //return b-a;降序
	}
	
	
	Date的一些方法
	var date = new Date(); //创建一个时间显示当前事件
	date.getFullYear();//获取当前年份
	date.getMonth()+1; //获取现在的月 必须+1
	date.getDate(); //获取现在的日
	date.getTime();//获取当前时间的毫秒数 可以在获取毫秒数后+上毫秒数再new Date(传入这个值);变为时间格式以后才可以get年月日时间等;
	date.getHours();//获取当前小时
	date.getMinutes();//获取当前分钟
	date.getSeconds();//获取当前秒数
	注分钟和秒数在小于10的时候打印的是一位数字,要好看需要方法设置
	var endTime=new Date("2018/1/1,0:00:00") //设定倒计时结束时间(自定义时间)
	date.setFullYear(2010,1,1);设置时间
	alert(date.toLocaleString());//输出框显示当前时间转换为时间string格式
	
	
	function jm(){           //编码解码测试   会对username值进行加码和解码
	   var address = "http://www.baidu.com?username='周杰伦'"
	   //编码
	   var r1 = window.encodeURI(address);
	   alert(r1);
	   //解码
	   var r2 = window.decodeURI(r1);
	   alert(r2);
	}
	
	
	<h2>arguments测试</h2>
	<input type="button" onclick="testargument(1,2,3,4,5)" value="arguments测试"/><br/><br/>
	<h2>eval测试</h2>
	<input type="button" onclick="testEval()" value="eval测试"/><br/><br/>
	
	function testargument(){        //没有形参,但是前台一样可以把参数传入进来(开发者无需明确指出参数名,就能访问它们)
	   alert(arguments[2]);
	}
	
	function testEval(){             //eval测试(对eval()括号里的内容进行计算处理)  执行str里面代码 alert输出括号里的123
	   var str = "alert(123)";
	   eval(str);
	}
	eval简单案例
	<h2>简单计算器</h2>
	         <input type="button" onclick="addCal(this.value)" value="1"/>
	         <input type="button" onclick="addCal(this.value)" value="2"/>
	         <input type="button" onclick="addCal(this.value)" value="3"/>
	         <input type="button" onclick="addCal(this.value)" value="4"/>
	         <input type="button" onclick="addCal(this.value)" value="+"/>
	         <input type="button" onclick="addCal(this.value)" value="-"/>
	         <input type="button" onclick="addCal(this.value)" value="="/><br/>
	         <input id="equal" style="210px;"/>
	function addCal(val){   //传入的是input标签的value值
	   var result = document.getElementById("equal").value;//取出input框中的内容
	   if(val == "="){
	      //执行输入框里面的字符串
	      var finalRes = eval(result);//可以对字符串进行运算
	      document.getElementById("equal").value = finalRes;//修改input框中的内容
	   }else{
	      result += val;//拼接字符串
	      document.getElementById("equal").value = result;//修改input框中的内容
	   }
	}
	*****js获取html标签修改css动画*****
	document.getElementById("baiduditu").style.webkitAnimation="key方法 2s 1";
	解决display和动画效果冲突
	需要用js获取标签修改display
	可以用 标签.style.opacity=1;使透明度渐变 体验感关度
	再用计时器延迟动画效果
	
	/*爬虫效果*/
	<meta charset="utf-8">
	<meta content="这是我做的京东" name="tzy">
	<meta content="爬虫来搜搜" name="rbn">
	
	
	
	                      常用正则
	
	var regex = new RegExp("\w{3,6}$","g");//定义一个正则表达式:3到6位数字或字母的组合
	regex.test(val)//判断是否满足正则
	
	String.replace(/mmp/gi,"*"); // 正则  g代表全局,  i忽略大小写
	
	
	                                                引用方式
	
	外部引用js
	js文件里面直接function 方法名参数{
	代码块
	}
	
	如:js文件
	function hello(){
	alert('hello,china');
	}
	html文件:
	<script type="text/javascript" language="javascript" src="js/testjs.js" charset="gb2312″></script>
	//charset修改当前HTML读取js格式
	<input type="button" value="第二种引入方式" onclick="hello()"/><br/><br/>
	
	
	内部引用js
	<script>
	function 方法名(参数){代码块}
	</script>
	
	如:
	html文件:
	<script>
	function hello1(){
	alert('hello,china');
	}
	</script>
	
	<input type="button" value="第二种引入方式" onclick="hello1()"/><br/><br/>
	
	
	
	内联式
	<input type="button" value="内联式" onclick="window.alert('hello world!')"/>
	
	
	
	innertext/innerhtml/outerhtml的区别
	event对象 
	
	e.preventDefault()
	该方法将通知 Web 浏览器不要执行与事件关联的默认动作(如果存在这样的动作)。例如,如果 type 属性是 "submit",在事件传播的任意阶段可以调用任意的事件句柄,通过调用该方法,可以阻止提交表单。注意,如果 Event 对象的 cancelable 属性是 fasle,那么就没有默认动作,或者不能阻止默认动作。无论哪种情况,调用该方法都没有作用。
	event.target()
	target 属性规定哪个 DOM 元素触发了该事件。
	event.relatedTarget
	relatedTarget 事件属性返回与事件的目标节点相关的节点。
	
	对于 mouseover 事件来说,该属性是鼠标指针移到目标节点上时所离开的那个节点。
	
	对于 mouseout 事件来说,该属性是离开目标时,鼠标指针进入的节点。
	
	对于其他类型的事件来说,这个属性没有用。
原文地址:https://www.cnblogs.com/ttzzyy/p/9522901.html