Javascript学习笔记

java:  https://www.cnblogs.com/tutut/p/7203840.html

1.在html中使用javascript

引入脚本

<script type="text/javascript" src="script_path"></script>
  • 1

直接嵌入代码

<script type="text/javascript">
    alert("hello world");
</script>
  • 1
  • 2
  • 3

需要注意的是当有src属性时,嵌入的代码会被忽略

其它常用属性

属性作用
defer 延迟 表示脚本延迟到文档完全被解析和显示之后再执行,只对外部脚本有效
async 异步 表示立即下载脚本,但不能影响其它操作,比如下载其它资源或等待加载其它脚本,只对外部脚本有效
type 说明脚本类型
src 包含外部脚本

关于defer与async的详细说明: 
defer的作用是让脚本延迟到整个页面都解析完毕后再运行,设置defer属性相当于告诉浏览器立即下载,但延迟到遇到</html>标签后再执行,html5规范要求脚本按照它们出现的先后顺序执行,并且先于DOMContentLoaded事件执行,但在现实中延迟脚本并不一定会按照顺序执行,也不一定会在DOMContentLoaded事件触发前执行 
async的作用是不让页面等待脚本下载和执行,从而异步加载页面其他内容,因此,异步脚本最好不要在加载期间修改DOM,异步脚本一定会在页面的load事件前执行,但可能会在DOMContentLoaded事件触发之前或之后执行,异步脚本不按照它们在页面出现的顺序执行

2.javascript类型一览

基本类型:undefined,null,boolean,number,string 
引用类型:object 
可以用typeof操作符查看类型,需要注意的是typeof并不是函数, 
可以用typeof(myvarlue)的形式,也可以用typeof myvarlue

typeof返回值说明

返回值出现情况
undefined 如果这个值未定义
boolean 如果这个值是布尔值
string 如果这个值是字符串
number 如果这个值是数值
object 如果这个值是对象或null
function 如果这个值是函数

来看一个例子

var str1 = 'hello world';
var str2
console.log(typeof str1); //string
console.log(typeof str2); //undefined
console.log(typeof str3); //undefined
console.log(typeof 66); //number
console.log(typeof null); //object
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

需要注意的是对声明了未初始化和未声明的变量执行typeof都返回undefined 
对于null返回object是因为null被认为是一个空的对象引用 
另外,undefined是派生自null的,因此以下相等性测试返回true

console.log(null == undefined); //true
  • 1

3.javascript Object类型

var animal1 = new Object();
//or animal = Object(); new可以省略
animal1.name = 'dog';
animal1.color = 'white';
console.log(animal1.name); //dog
console.log(animal1['color']); //white
//另一种方式创建对象
var animal2 = {}; //此方式其实并没有调用Object构造函数
animal2.name = 'cat';
//带初始化值
var animal3 = Object({name:'cat',age:10});
var animal4 = {name:'cat',age:10};
  • 1

4.javascript Function类型

3种创建函数的方式

//第一种
function hello(name)
{
    alert('hello ' + name);
}
//第二种
var hello = function(name)
{
    alert('hello ' + name);
};
//第三种
var hello = new Function('name','alert("hello " + name)');

这三种方式不推荐使用第三种,因为第三种语法会导致解析两次代码从而影响性能,关于第一种和第二种的区别见下例

//调用在声明前面,但结果仍然正确
hello('world');
function hello(name)
{
    alert('hello ' + name);
}
//调用在声明前面,会出错
hello('world');
var hello = function(name)
{
    alert('hello ' + name);
}

这是因为用第一种方式时,解析器会率先读取函数声明,并使其在执行任何代码之前可用;而对于第二种方式,则必须等到解析器执行到它所在的代码行,才会真正被解释执行。

javascript的函数在对待参数方面是比较特殊的。它不介意传递进去多少个参数,也不在乎传递进来的参数是什么数据类型。也就是说,即便你定义的函数只接收两个参数,在调用这个函数时也未必一定要传递两个参数,可以传递一个,三个甚至不传递参数,而解析器永远不会有什么怨言。之所以会这样,是因为ECMAScript中的参数在内部是用一个数组来表示的。函数接收到的始终是这个数组,而不关心数组中包含哪些参数。如果这个数组中不包含任何元素,无所谓;如果包含多个元素,也没有问题。在函数内部可以通过arguments对象来访问这个参数数组。

一个例子

function hello(name)
{
    console.log('hello ' + name);
    console.log('hello ' + arguments[0]);
    console.log('hello ' + arguments[1]);
    console.log('hello ' + arguments[2]);
    console.log(arguments.length);
}
hello('world','you');
//结果为
//hello world
//hello world
//hello you
//hello undefined
//2

javascript的函数实际上是对象。函数也有属性和方法。每个函数都有两个属性:length和prototype。length表示函数希望接收的参数个数,prototype是保存实例方法的真正所在。每个函数都包含两个方法:apply()和call(),这两个函数的作用都是在特定的作用域中调用函数,apply()接收两个参数,一个是作用域,另一个是参数数组,第二个参数可以是Array,也可以是arguments对象,call()与apply()的不同之处在于参数的传递方式。

一个例子

function hello1(name)
{
    alert('hello' + name);
}
function hello2()
{
    alert('hello')
}
hello1.length; //1
hello2.length; //0
function sum(num1,num2)
{
    return num1 + num2;
}
function callSum1(num1,num2)
{
    return sum.apply(this,arguments);
}
function callSum2(num1,num2)
{
    return sum.apply(this,[num1,num2]);
}
function callSum3(num1,num2)
{
    return sum.call(this,num1,num2);
}
callSum1(10,10); //20
callSum2(10,10); //20
callSum3(10,10); //20
//通过call扩充函数的作用域
var color = 'red';
var o = {color:'blue'};
function sayColor()
{
    console.log(this.color);
}
sayColor(); //red
sayColor.call(this); //red
sayColor.call(window); //red
sayColor.call(o); //blue
  • 1
  • 2
  • 5.javascript String类型

主要是与string相关的函数的使用,直接看例子吧

var str1 = 'hello';
//输出指定位置字符
str1.charAt(0); //h
//输出指定位置字符的编码
str1.charCodeAt(0); //104
//通过索引访问
str1[0]; //h
//连接字符串
str1.concat(' world'); //hello world
//slice
str1.slice(1); //ello
str1.slice(1,3); //el
//substring
str1.substring(1); //ello
str1.substring(1,3); //el
//substr,注意与slice与substring的区别
str1.substr(1); //ello
str1.substr(1,3); //ell
//indexof lastIndexOf
str1.indexOf('l'); //2
str1.indexOf('l',3); //3
str1.lastIndexOf('l'); //3
str1.lastIndexOf('l',2); //2
//trim 删除前后空格
var str2 = ' hello ';
str2.trim(); //hello
//大小写转换
var str3 = 'Hello';
str3.toLowerCase(); //hello
str3.toUpperCase(); //HELLO
//模式匹配
vat str4 = 'hello world';
var pattern = /hello/;
//match
var matches = str4.match(pattern);
matches.index; //0
matches[0]; //hello
//search 返回第一个匹配项的索引,没有匹配项则返回-1
str4.search(pattern); //0
//replace
str4.replace('l','x'); //hexlo world
str4.replace(/l/g,'x'); //hexxo worxd
//split
var colors = 'red,blue,green,yellow';
colors.split(','); //['red','blue','green','yellow']
colors.split(',',2); //['red','blue']
colors.split(/[^\,]+/); //['',',',',',',','']
//字符串比较 localeCompare
var str5 = 'hello';
str5.localeCompare('world'); //-1
str5.localeCompare('black'); //1
str5.localeCompare('hello'); //0
//fromCharCode 将字符编码转换成相应字符
String.fromCharCode(104,101,108,108,111); //hello

以上所有方法都不会改变原字符串,另外上面对replace方法介绍比较简略,下面详细说明一下 
直接看例子

var str = 'left hello world right';
//$n 引用分组
str.replace(/(hello) (world)/,'$2 $1'); //left world hello right
//$$ 表示$
str.replace(/(hello) (world)/,'$$'); //left $ right
//$& 表示匹配的项
str.replace(/(hello) (world)/,'$&'); //left hello world right
//$' 表示匹配项之后的字符串
str.replace(/(hello) (world)/,"$'"); //left right right
//$` 表示匹配项之前的字符串
str.replace(/(hello) (world)/,'$`'); //left left right
  • 11

另外,replace的第二个参数也可以是函数。在只有一个匹配项时,会向这个函数传递3个参数:模式的匹配项,模式匹配项在字符串中的位置和原始字符串。在正则表达式中定义了多个捕获组的情况下,传递给函数的参数依次是模式的匹配项,第一个捕获组的匹配项,第二个捕获组的匹配项……,但最后两个参数仍然分别是模式的匹配项在字符串中的位置和原始字符串,这个函数应该返回一个字符串作为替换文本。

来看一个摘自Javascript高级程序设计(第三版)的例子

function htmlEscape(text)
{
    return text.replace(/[<>"&]/g,function(match,pos,originalText){
        switch(match){
            case "<":
                return "&lt;";
            case ">":
                return "&gt;";
            case "&":
                return "&amp;";
            case """:
                return "&quot;";
        }
    });
}
htmlEscape("<p class="greeting">hello world!</p>");
//&lt;p class=&quot;greeting&quot;&gt;hello world!&lt;/p&gt;
  • 1

6.javascript Date类型

var mytime = new Date();
mytime.getFullYear(); //四位的年份
mytime.getMonth(); //月份
mytime.getDate(); //天数
mytime.getDay(); //星期
mytime.getHours(); //小时
mytime.getMinutes(); //分钟
mytime.getSeconds(); //秒数
mytime.getMilliseconds(); //毫秒数
mytime.toLocaleString(); //与特定时区相关的时间格式
Date.now(); //总毫秒数
//设置时间,表示 2015年9月20号17时20分30秒
//月份是用0-11表示的,所以8表示9月
var mytime1 = new Date(2015,8,20,17,20,30);

7.javascript RegExp类型

创建正则表达式的方法 
var mypattern = /pattern/flags 或 
var mypattern = new RegExp(‘pattern’,’flags’) 
由于用构造函数创建时可能需要双重转义,所以用第一种方式有时更简洁

flags的取值

作用
g 表示全局模式,即模式被应用于所有的字符串,而非发现第一个匹配项时立即停止
i 忽略大小写
m 多行模式,即在到达一行文本末尾时还会继续查找下一行中是否存在模式匹配的项

一个例子

var mypattern1 = /hello/i;
var mypattern2 = /hello/;
//test方法用来测试给定字符串中是否存在匹配模式
mypattern1.test('Hello world'); //true
mypattern2.test('Hello world'); //false
//RegExp实例属性
//是否设置了g标志
mypattern1.global; //false
//是否设置了i标志
mypattern1.ignoreCase; //true
//开始搜索下一个匹配项的字符位置,从0算起
mypattern1.lastIndex; //0
//是否设置了m标志
mypattern1.multiline; //false
//正则表达式的字符串表示,按照字面量形式返回
mypattern1.source; //hello

//exec
var mypattern3 = /(he)l(lo)/i;
var matches = mypattern3.exec('Hello world');
//匹配项在字符串中的位置
matches.index; //0
//输入的字符串
matches.input; //Hello world
//匹配到的字符串
matches[0]; //Hello
//匹配到的第一个分组
matches[1]; //He
//匹配到的第二个分组
matches[2]; //lo
//匹配到的第三个分组,在此没有第三个分组,为undefined
matches[3]; //undefined

对exec的补充说明:对于exec而言,即使在模式中设置了全局标志(g),它每次也只返回一个匹配项。在不设置全局标志的情况下,在同一个字符串上多次调用exec将始终返回第一个匹配项的信息。而在设置全局标志的情况下,每次调用exec则都会在字符串中继续查找新匹配项。

8.javascript Array类型

var animal1 = new Array();
//or var animal = Array()
//指定数组长度
var animal2 = Array(10);
//带初始化值
var animal3 = Array('dog','cat','fox');
//另一种方式
var animal4 = []; //并没有调用Array构造函数
var animal5 = ['mouse','cat'];
//访问元素
console.log(animal5[0]); //mouse
console.log(animal5.length); //2
//检测数组
Array.isArray(animal5); //true

一些方法,假定数组名为myarr

名称作用
myarr.toString() 返回数组的字符串表示,以逗号分隔,为了取得每一项的值调用每一项的toString()方法
myarr.valueOf() 还是返回这个数组
myarr.toLocaleString() 返回数组的字符串表示,为了取得每一项的值调用每一项的toLocaleString()方法
myarr.join() 返回数组的字符串表示,默认以逗号分隔,可以自己指定分隔符
myarr.push() 在末尾添加元素,参数个数不限,返回修改后的数组长度
myarr.pop() 移除末尾项,返回移除的元素
myarr.shift() 移除第一项,返回移除的元素
myarr.unshift() 在头部添加元素,参数个数不限,返回修改后的数组长度
myarr.sort() 正向排序,此方法默认是按字符串比较的方式排序的(即使是数字),可以给它传递一个比较函数来自定义比较行为,比较函数接收两个参数,如果第一个参数位于第二个参数之前则返回一个负数,相等返回0,之后返回正数,此方法返回经过排过序的数组
myarr.reverse() 反向排序,其它同sort
myarr.concat() 基于数组的项以及参数的项创建一个新数组并返回
myarr.slice() 基于数组中的一个或多个项创建一个新数组并返回,可以接受一或两个参数来指明返回项的起始和结束位置(包含起始位置项,不包含结束位置项),若不传递参数返回所有项,传递一个参数时结束位置默认为末尾
myarr.splice() 参数个数不限,第一参数指定要删除元素的第一项位置,第二个参数指定要删除的项数,后续参数指定插入的元素,返回由删除的元素组成的数组
myarr.indexOf() 正向查找,接收两个参数,第一个为要查找的项,第二个为表示查找起点位置的索引(可选,默认从开头查找),如果没找到返回-1,找到的话返回索引
myarr.lastIndexOf() 反向查找,其它同indexOf

一个例子

//sort reverse
var myarr1 = [1,2,15,10,9];
myarr1.sort(); //[1,10,15,2,9]
function mycompare(value1,value2)
{
    return value1 - value2;
}
myarr1.sort(mycompare); //[1,2,9,10,15]
myarr1.reverse(mycompare); //[15,10,9,2,1]
//concat
var myarr2 = [1,2];
myarr2.concat(); //[1,2]
myarr2.concat(3); //[1,2,3]
myarr2.concat(3,['white','black']); //[1,2,3,'white','black']
//slice
var myarr3 = [1,2,3,4,5];
myarr3.slice(); //[1,2,3,4,5]
myarr3.slice(1); //[2,3,4,5]
myarr3.slice(1,3); //[2,3]
myarr3.slice(1,1); //[]
//splice
var myarr4 = [1,2,3,4];
myarr4.splice(0,1); //返回[1]
console.log(myarr4); //[2,3,4]
myarr4.splice(0,0,'white','black'); //返回[]
console.log(myarr4); //['white','black',2,3,4]
//indexOf lastIndexOf
var myarr5 = ['white','black','pink','white'];
myarr5.indexOf('white'); //0
myarr5.lastIndexOf('white'); //3
myarr5.indexOf('white',1); //3
myarr5.lastIndexOf('white',2); //0
myarr5.indexOf('yellow'); //-1
  • 1
  • 2

以下方法为迭代方法,每个方法都接收两个参数:要在每一项上运行的函数和(可选的)运行该函数的作用域对象,这些方法都不改变原数组。传入这些方法中的函数会接收三个参数:数组项的值,该项在数组中的位置和数组对象本身。在此假定数组名为myarr

方法名作用
myarr.every() 对数组中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true
myarr.filter() 对数组中的每一项运行给定函数,返回该函数会返回true的项组成的数组
myarr.forEach() 对数组中的每一项运行给定函数,无返回值
myarr.map() 对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组
myarr.some() 对数组的每一项运行给定函数,只要存在某一项让函数返回true,就返回true

一个例子

function myfunc1(item,index,array)
{
    return item > 2;
}
function myfunc2(item,index,array)
{
    return item % 2 == 0;
}
function myfunc3(item,index,array)
{
    return item * 2;
}
function myfunc4(item,index,array)
{
    console.log(item);
}
var myarr = [1,2,3,4,5];
//every
myarr.every(myfunc1); //false
//some
myarr.some(myfunc1); //true
//filter
myarr.filter(myfunc2); //[2,4]
//map
myarr.map(myfunc3); //[2,4,6,8,10]
//forEach
myarr.forEach(myfunc4); //1 2 3 4 5

最后再介绍两个方法reduce()和reduceRigth()。这两个方法都会迭代数组的所有项,然后构建一个最终返回的值。区别是reduce从前往后,reduceRight从后往前。这两个方法都接收两个参数:一个在每一项上调用的函数和(可选的)初始值。传递给它俩的函数接收4个参数:前一个值,当前值,项的索引和数组对象。

一个例子

function mysum(prev,cur,index,array)
{
    return prev + cur;
}
myarr = [1,2,3];
myarr.reduce(mysum); //6
myarr.reduce(mysum,5); //11

9.javascript Global对象

在javascript中,不属于任何其他对象的属性和方法,最终都是Global对象的属性和方法。事实上,没有全局变量或全局函数,所有全局作用域中定义的属性和函数,都属于Global对象。ECMAScript虽然没有指出如何直接访问Global对象,但web浏览器都是将这个全局对象作为window对象的一部分加以实现的。因此,在全局作用域中声明的所有变量和函数就都成了window对象的属性。 
除了用window对象,我们可以用下列方式获得Global对象

var global = function(){
    return this;
}();

在此介绍一些Global对象比较有用的方法 
首先是URI编码方法,看例子

//encodeURI
var uri = 'http://www.test.com/illegal value.html?user=username';
encodeURI(uri);
//http://www.test.com/illegal%20value.html?user=username
//encodeURIComponent
encodeURIComponent(uri);
//http%3A%2F%2Fwww.test.com%2Fillegal%20value.html%3Fuser%3Dusername
//另外可以用decodeURI和decodeURIComponent对编码的结果解码

它们的区别是encodeURI不会对本身属于URI的特殊字符进行编码,例如冒号,正斜杠,问号等;而encodeURIComponent()则会对它发现的任何非标准字符进行编码。

另一比较有用的方法是eval 
eval接收一个参数,它会把传入的参数当代码执行,看下面的例子

eval('2 + 3 * 4'); //14
eval("alert('hello world')"); //hello world

10.BOM

取得窗口位置

var leftPos = (typeof window.screenLeft == 'number') ?
                window.screenLeft : window.screenX;
var topPos = (typeof window.screenTop == 'number') ?
                window.screenTop : window.screenY;
//这样写主要是保持兼容性,有的浏览器只支持screenLeft,有的只
//支持screenX,有的都支持
  • 6

移动窗口与调整窗口大小

//moveTo 两个参数:新位置的x和y坐标
//moveBy 两个参数:水平和垂直方向上移动的像素数
//resizeTo 两个参数:新宽度与新高度
//resizeBy 两个参数:新窗口与原窗口的宽度和高度之差
//这四个方法可能会被浏览器禁用
window.moveTo(50,100);
window.moveBy(20,20);
window.resizeTo(300,300);
window.resizeBy(20,-10);

取得页面视图的大小

var pageWidth = window.innerWidth;
var pageHeight = window.innerHeight;
if(typeof pageWidth != 'number')
{
    if(document.compatMode == 'CSS1Compat')
    {
        pageWidth = document.documentElement.clientWidth;
        pageHeight = document.documentElement.clientHeight;
    }else{
        pageWidth = document.body.clientWidth;
        pageHeight = documetn.body.clientHeight;
    }
}

间歇调用与超时调用

//1秒后执行函数
var timeoutId = setTimeout(function(){alert('hello world');},1000);
//取消调用
clearTimeout(timeoutId);
//每隔1秒执行一次函数
var intervalId = setInterval(function(){alert('hello world');},1000);
//取消调用
clearInterval(intervalId);
  • 8

系统对话框

//prompt 第一个参数是显示给用户的文本提示
//       第二个参数是文本框中的默认值
var expre = prompt("输入表达式","expression");
alert(eval(expre));
if(confirm('你认为结果对吗'))
{
    alert('Very good');
}else{
    alert('Sorry');
}

location对象

属性名作用
hash 返回URL中#后的字符(包含#号)
host 返回服务器名和端口号
hostname 返回不带端口号的服务器名称
href 返回完整的URL
pathname 返回URL中的目录和文件名
port 返回端口号
protocol 返回协议,http:或https:
search 返回查询字符串,例如:’?name=username’
//打开指定网址
location.assign('http://www.test.com'); //或
window.location = 'http://www.test.com'; //或
location.href = 'http://www.test.com'; //或
location.replace('http://www.test.com');
//replace与上面三种方法的区别是它不会在历史记录中生成新记录
//因此不能通过后退按钮回到前一个页面

//重新加载
location.reload(); //有可能从缓存加载
location.reload(true); //强制从服务器加载

navigator对象 
此对象属性很多,在此只列举常用的

//检测插件(非ie)
for(var i=0;i<navigator.plugins.length;i++)
{
    console.log(navigator.plugins[i].name);
}
//浏览器名称
navigator.appName;
//cookie是否启用
navigator.cookieEnabled;
//浏览器所在的系统平台
navigator.platform;
//浏览器的用户代理字符串
navigator.userAgent;

history对象

history.go(-1); //后退一页
history.go(2); //前进两页
history.go('test.com'); //跳转到历史记录中包含'test.com'的第一个位置
//可能后退,也可能前进,具体看哪个位置最近
history.forward(); //前进一页
history.back(); //后退一页
history.length; //历史记录的数量

11.DOM

节点类型

英文表示对应的数字
ELEMENT_NODE 1
ATTRIBUTE_NODE 2
TEXT_NODE 3
CDATA_SECTION_NODE 4
ENTITY_REFERENCE_NODE 5
ENTITY_NODE 6
PROCESSING_INSTRUCTION_NODE 7
COMMENT_NODE 8
DOCUMENT_NODE 9
DOCUMENT_TYPE_NODE 10
DOCUMENT_FRAGMENT_NODE 11
NOTATION_NODE 12
//确定节点类型
//在ie中无效
if(someNode.nodeType == Node.ELEMENT_NODE)
{
    alert("Node is an element");
}
//适用于所有浏览器
if(someNode.nodeType == 1)
{
    alert("Node is an element");
}

节点的属性及方法

//读取节点属性的方法
someNode.nodeName; //标签名
someNode.nodeValue; //值
someNode.parentNode; //父节点
someNode.firstChild;
someNode.lastChild;
someNode.previousSibling; //同一列表中someNode的前一节点
someNode.nextSibling; //同一列表中someNode的后一节点
someNode.hasChildNodes(); //有子节点时返回true
var firstChild = someNode.childNodes[0];
var secondChild = someNode.chileNodes.item(1);
var count = someNode.childNodes.length;

//改变节点
someNode.appendChild(newNode);
someNode.insertBefore(newNode,someNode.firstChild);
someNode.replaceChild(newNode,someNode.firstChild);
someNode.removeChild(someNode.firstChild);
var newNode = oldNode.cloneNode(true); //深复制,若参数是false则为浅复制

document对象

document.documentElement; //取得对<html>的引用
document.title; //取得文档标题
document.body; //取得对<body>的引用
document.URL; //取得完整的URL
document.domain; //取得域名
document.referrer; //取得来源页面的URL

//取得元素
document.getElementById("id");
document.getElementsByTagName("img");
document.getElementsByName("color");
document.anchors; //包含文档中所有带name特性的<a>元素
document.forms; //包含文档中的所有<form>元素
document.images; //包含文档中的所有<img>元素
document.links; //包含文档中所有带href特性的<a>元素

//特性
someNode.getAttribute("attributeName");
someNode.setAttribute("attributeName","value");
someNode.removeAttribute("attributeName");

//创建元素
var div = document.createElement("div");
div.id = "mydiv";
div.className = "box";

//创建文本节点
var textNode = document.createTextNode("hello");
textNode.appendData(text); //将text添加到节点的末尾
textNode.deleteData(offset,count); //从offset指定的位置开始删除count个字符
textNode.insertData(offset,text); //在offset指定的位置插入text
textNode.replaceData(offset,count,text); 
//用text替换从offset指定的位置开始到offset+count位置处的文本
textNode.splitText(offset); 
//从offset指定的位置将当前文本分成两个文本节点
textNode.substringData(offset,count); 
//提取从offset指定位置开始到offset+count为止处的字符串

dom扩展

//querySelector
document.querySelector("body"); //取得body元素
document.querySelector("#mydiv"); //取得id为mydiv的元素
document.querySelector(".classname"); //取得类为classname的第一个元素
document.body.querySelector("img.button"); //取得类为button的第一个图象元素

//querySelectorAll
document.querySelectorAll(".classname"); //取得类为classname的所有元素
document.querySelectorAll("p strong"); //取得所有<p>元素中的所有<strong>元素

//dom元素新属性
myNode.childElementCount; //返回子元素(不包含文本节点和注释)的个数
myNode.firstElementChild; //第一个元素
myNode.lastElementChild; //最后一个元素
myNode.previousElementSibling; //前一个同辈元素
myNode.nextElementSilling; //后一个同辈元素

html5新规范

//取得指定类名的元素,类名的先后顺序无所谓
document.getElementsByClassName("username current");

//<div class="bd user disabled"></div>
div.classList.remove("user"); //删除user
div.classList.toggle("user"); //有user删除,没有添加
div.classList.add("user"); //无user添加,有不添加
div.classList.contains("user"); //存在user返回true,否则返回false

//焦点管理
var button = document.getElementById("myButton");
button.focus();
document.activeElement === button; //true
button.hasFocus(); //true

//其它
document.readyState;
//若为loading,表示正在加载文档,若为complete,表示已经加载完文档
document.compatMode;
//若为CSS1Compat,表示标准模式,若为BackCompat,表示混杂模式
document.head; //引用<head>元素
document.charset = "utf-8"; //字符编码

//<div id="content"><p>la</p></div>
var div = document.getElementById("content");
div.innerHTML; //<p>la</p>
div.outerHTML; //<div id="content"><p>la</p></div>
//insertAdjacentHTML
//两个参数:插入位置和要插入的HTML文本
//作为前一个同辈元素插入
element.insertAdfacentHTML("beforebegin","<p>la</p>");
//作为第一个子元素插入
element.insertAdjacentHTML("afterbegin","<p>la</p>");
//作为最后一个子元素插入
element.insertAdjacentHTML("beforeend","<p>la</p>");
//作为最后一个同辈元素插入
element.insertAdjacentHTML("afterend","<p>la</p>");

//scrollIntoView
//传入true或不传参数那么窗口滚动之后会让调用元素的顶部与视口顶部尽可能平齐
//传入false调用元素会尽可能全部出现在视口中
document.forms[0].scrollIntoView();

添加与移除事件

var btn = document.getElementById("myBtn");
var handler = function(){alert(this.id);};
btn.addEventListener("click",handler,false);
//false表示在冒泡阶段调用事件处理程序,若为true则表示在捕获阶段调用处理程序
btn.removeEventListener("click",handler,false); //移除事件

//一个通用的事件添加与移除程序
var EventUtil = {
    addHandler:function(element,type,handler){
        if(element.addEventListener){
            element.addEventListener(type,handler,false);
        else if(element.attachEvent){
            element.attachEvent("on"+type,handler);
        else{
            element["on"+type] = handler;
        }
    }
    removeHandler:function(element,type,handler){
        if(element.removeEventListener){
            element.removeEventListener(type,handler,false);
        }else if(element.detachEvent){
            element.detachEvent("on"+type,handler);
        else{
            element["on"+type] = null;
        }
    }
};

ui事件

事件名说明
load 当页面完全加载后在window上面触发,当所有框架都加载完毕时在框架集上面触发,当图象加载完毕时在<img>元素上面触发,或者当嵌入的内容加载完毕时在≶object>元素上面触发
unload 当页面完全卸载后再window上面触发,当所有框架都卸载后再框架集上面触发,或者当嵌入的内容卸载完毕后再<object>元素上面触发
abort 在用户停止下载过程时,如果嵌入的内容没有加载完,则在<object>上面触发
error 当发生javascript错误时在window上面触发,当无法加载图像时在<img>元素上面触发,当无法加载嵌入内容时在<object>元素上面触发,或者当有一或多个框架无法加载时在框架集上面触发
select 当用户选择文本框中的一或多个字符时触发
resize 当窗口或框架的大小变化时在window或框架上面触发
scroll 当用户滚动带滚动条的元素中的内容时,在该元素上面触发

焦点事件

事件名说明
blur 在元素失去焦点时触发,这个事件不会冒泡
focus 在元素获得焦点时触发,这个事件不会冒泡
focusin 在元素获得焦点时触发,会冒泡
focusout 在元素失去焦点时触发,会冒泡

鼠标与滚轮事件

事件名说明
click 单击鼠标按钮或按下回车时触发
dblclick 双击鼠标按钮时触发
mousedown 按下任意鼠标按钮时触发
mouseenter 在鼠标光标从元素外部首次移到元素范围之内时触发,不冒泡
mouseleave 在位于元素上方的鼠标光标移到元素范围之外时触发,不冒泡
mousemove 当鼠标指针在元素内部移动时重复的触发
mouseout 当鼠标指针位于一个元素上方,然后用户将其移入另一个元素时触发
mouseover 在鼠标指针位于一个元素外部,然后用户将其首次移入另一个元素边界之内时触发
mouseup 在用户释放鼠标按钮时触发

键盘与文本事件

事件名说明
keydown 当用户按下键盘的任意键时触发,如果按住不放会重复触发该事件
keypress 当用户按下键盘的字符键时触发,如果按住不放会重复触发该事件
keyup 当用户释放键盘上的键时触发
textInput 在文本插入文本框之前会触发textInput事件

表单相关

var form = document.getElementById("myform");
form.submit(); //提交表单
form.reset(); //重置表单
var field1 = form.elements[0]; //取得表单第一个字段
var field2 = form.elements["textbox1"]; //取得名为textbox1的字段
var fieldCount = form.elements.length;

//取得选择的文本
textbox.value.substring(textbox.selectionStart,textbox.selectionEnd);

html5验证

/*
<input type="text" name="username" required>
<input type="email" name="email">
<input type="url" name="homepage">
<input type="number" min="0" max="100" step="5" name="count">
<input type="text" pattern="d+" name="count">
*/
//必填字段没有值是无效的,字段中的值与pattern不匹配也是无效的
if(document.forms[0].elements[0].checkValidity()){
    //有效时执行的代码
}else{
    //无效时执行的代码
}

12.JSON

用JSON.stringify()序列化Javascript对象 
用JSON.parse()将json格式的数据转成Javascript对象

var book = {
    title:"JavaScript",
    authors:"John",
    edition:3
};
var jsonText = JSON.stringify(book);
jsonText; 
//{"title":"JavaScript","authors":"John","edition":3}
JSON.parse(jsonText); 
//Object {title: "JavaScript", authors: "John", edition: 3}

JSON.stringify()还可以接收另外两个参数 
第一个是过滤器,可以是数组也可以是函数 
第二个是一个选项,表示是否在JSON字符串中保留缩进

var book = {
    title:"JavaScript",
    authors:["John","Mike"],
    edition:3
};
var jsonText = JSON.stringify(book,['title','authors']);
jsonText;
//{"title":"JavaScript","authors":["John","Mike"]}
var myfun = function(key,value){
    switch(key){
        case "authors":
            return value.join(",");
        case "edition":
            return undefined;
        default:
            return value;
    }
}
jsonText = JSON.stringify(book,myfun);
//{"title":"JavaScript","authors":"John,Mike"}
//如果返回undefined,相应属性会被忽略
//每个级别缩进4个空格
JSON.stringify(book,myfun,4);
//{
//    "title": "JavaScript",
//    "authors": "John,Mike"
//}
//设置缩进字符
JSON.stringify(book,myfun,"--");
//{
//--"title": "JavaScript",
//--"authors": "John,Mike"
//}
  • 33

JSON.parse()可以接收第二个参数,该参数是函数,其用法与JSON.stringify的第二个参数类似。另外对象还有toJSON方法,假如把一个对象传入JSON.stringify(),序列化该对象的顺序如下: 
1.如果存在toJSON()方法而且能通过它取得有效的值,则调用该方法,否则按默认顺序执行序列化。 
2.如果提供了第二个参数,应使用这个函数过滤器,传入函数过滤器的值是第1步返回的值。 
3.对第2步返回的每个值进行相应的序列化。 
4.如果提供了第三个参数,执行相应的格式化。

13.Ajax

get请求

var xhr = new XMLHttpRequest();
xhr.open("get","test.php",false); //false表示同步请求
xhr.send(null);
if( (xhr.status>=200 && xhr.status<300) || xhr.status==304 ){
    alert(xhr.responseText);
}else{
    alert("Request was unsucessful:" + xhr.status);
}
  • var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if ((xhr.status>=200 && xhr.status < 300) || xhr.status == 304){
            alert(xhr.responseText);
        }else{
            alert("Request was unsuccessful:" + xhr.status);
        }
    }
};
xhr.open("get","test.php",true); //异步发送请求
xhr.send(null);

http头部信息

名称说明
Accept 浏览器能够处理的内容类型
Accept-Charset 浏览器能够显示的字符集
Accept-Encoding 浏览器能够处理的压缩编码
Accept-Language 浏览器当前设置的语言
Connection 浏览器与服务器之间连接的类型
Cookie 当前页面设置的任何Cookie
Host 发出请求的页面所在的域
Referer 发出请求的页面的URI
User-Agent 浏览器的用户代理字符串
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if ((xhr.status>=200 && xhr.status < 300) || xhr.status == 304){
            alert(xhr.responseText);
        }else{
            alert("Request was unsuccessful:" + xhr.status);
        }
    }
};
xhr.open("get","test.php",true); //异步发送请求
//设置要发送的头部信息
//最好不要使用浏览器正常发送的字段名称
//并且有的浏览器允许开发人员重写默认的头部信息
//但有的浏览器不允许这样做
xhr.setRequestHeader("myHeader","myValue");
//取得指定头部的信息
xhr.getResponseHeader("Use-Agent");
//取得所有头部信息
xhr.getAllResponseHeaders();
xhr.send(null);

post请求

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
        if ((xhr.status>=200 && xhr.status < 300) || xhr.status == 304){
            alert(xhr.responseText);
        }else{
            alert("Request was unsuccessful:" + xhr.status);
        }
    }
};
xhr.open("post","test.php",true); //异步发送请求
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var data = "username=John&hobby=running";
//还可以用FormData
//var form = document.getElementById("user-info");
//var data = new FormData(form);
xhr.send(data);
  • 可以用overrideMimeType方法确保以某种方式处理返回的内容
//确保把响应当作xml而非纯文本来处理
//此方法必须在send方法之前调用
xhr.overrideMimeType("text/xml");
原文地址:https://www.cnblogs.com/klb561/p/8725936.html