@GivenCui
        
        2016-06-17T10:54:09.000000Z
        字数 115506
        阅读 2045
    js上机练习
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>名片管理器</title></head><body><script type="text/javascript">/*需求:名片管理器管理名片构造函数:名片、名片管理器名片属性:姓名、公司、电话、邮箱名片管理器属性:名片数组名片管理器方法:添加名片、显示所有名片信息、删除名片*///名片构造函数function Card (name, company, phoneNum, mail) {this.name = name;this.company = company;this.phoneNum = phoneNum;this.mail = mail;}//名片管理器构造函数function CardManager () {//名片数组的属性,用来存储名片的this.cards = new Array();}//添加名片的方法CardManager.prototype.addCard = function (newCard) {//把名片添加到管理器的名片数组里this.cards.push(newCard);}//显示所有名片信息的方法CardManager.prototype.showAllCardInfo = function () {//通过循环遍历卡片数组得到每个卡片对象for (var i = 0; i < this.cards.length; i++) {var tempCard = this.cards[i];//格式化输出卡片信息console.log(" \n 名字:" + tempCard.name + " \n 公司:" + tempCard.company + " \n 电话:" + tempCard.phoneNum + " \n 邮箱:" + tempCard.mail);}}//模仿indexOf方法Array.prototype.myIndexOf = function (removeCard) {//this指向的是当前的数组对象for (var i = 0; i < this.length; i++) {if (this[i] === removeCard) {return i;}}return -1;}//模拟其他面向对象语言的按照指定元素删除的方法Array.prototype.removeObj = function (removeObj) {//this指向的是当前的数组对象var idx = this.myIndexOf(removeObj);//判断找没找到if (idx > -1) {this.splice(idx, 1);return;}console.log("没有找到要删除的名片!");}//删除名片的方法(因为JS中,没有按照指定元素删除的方法,所以我们要通过给数组构造函数的原型添加额外的方法)CardManager.prototype.removeCard = function (removeCard) {//调用咱们自己写的删除方法this.cards.removeObj(removeCard);}//创建名片管理器对象var cardManager = new CardManager();//创建很多名片对象var card1 = new Card("刘轶佳", "育知同创", "18688889999", "liuyijia@163.com");var card2 = new Card("李慧玲", "育知同创", "13600005555", "lihuiling@126.com");var card3 = new Card("刘升旭", "苹果", "18612597091", "278305920@qq.com");//添加名片 (数组是有序可以重复的)cardManager.addCard(card2);cardManager.addCard(card3);cardManager.addCard(card1);//显示所有名片信息cardManager.showAllCardInfo();//删除指定名片cardManager.removeCard(card3);//打印分隔符console.log("---------------------");//显示所有名片信息cardManager.showAllCardInfo();var card4 = new Card("abc", "ddd", "1833", "sdf@174.com");//删除指定名片cardManager.removeCard(card4);//打印分隔符console.log("---------------------");//显示所有名片信息cardManager.showAllCardInfo();</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>书签管理器</title></head><body><script type="text/javascript">/*需求:通过书签管理器来管理网页中的书签项。具备书签的增删改查功能。构造函数:书签管理器、书签书签的属性:网址、标题、星级书签管理的属性:书签数组书签管理的方法:1、添加书签(要求:不能重复添加标题或网址,也就是说只要符合一个条件就不让添加)2、显示所有标签信息(要求:按照星级排序)3、删除标签(通过标题删除)4、修改标签(通过标题去修改)*///书签构造函数function Book (url, title, star) {this.url = url;this.title = title;this.star = star;}//书签管理器构造函数function BookManager () {//属性:书签数组,用来存储很多书签的this.books = new Array();}//添加书签的方法(要求:不能重复添加标题或网址,也就是说只要符合一个条件就不让添加)BookManager.prototype.addBook = function (newBook) {//通过遍历得到书签数组中的每一个书签,目的是和新加的书签做判断。for (var i = 0; i < this.books.length; i++) {//得到每一个书签对象var tempBook = this.books[i];//判断新加的书签对象的标题或网址是否和之前存在的书签的标题或网址相同。if (tempBook.title === newBook.title || tempBook.url === newBook.url) {console.log("不能重复添加网址!");//return; 函数结束return;}}//经过循环判断没有重复的,就可以添加新书签this.books.push(newBook);}//显示所有标签信息的方法(要求:按照星级排序)BookManager.prototype.showAllBookInfo = function () {//冒泡排序,星级从小到大排序for (var i = 0; i < this.books.length - 1; i++) {for (var j = 0; j < this.books.length - 1 - i; j++) {//把位置为j 和 j +1的对象取出来var tempBook1 = this.books[j];var tempBook2 = this.books[j + 1];//判断相邻两个对象的星级属性大小if (tempBook1.star >= tempBook2.star) {//利用数组的splice函数,来实现数组两个位置元素的替换this.books.splice(j, 1, tempBook2);this.books.splice(j + 1, 1, tempBook1);}}}//格式化输出书签信息for (var i = 0; i < this.books.length; i++) {//得到每一个书签对象var tempBook = this.books[i];console.log(" \n 标题:" + tempBook.title + " \n 网址:" + tempBook.url + " \n 星级:" + tempBook.star);}}//给数组构造函数的原型添加方法(查找元素的下标)Array.prototype.myIndexOf = function (removeTitle) {for (var i = 0; i < this.length; i++) {//得当每一个数组里的对象var tempObj = this[i];//判断该对象的title属性 是否等于 要删除的title//如果相等,就说明找到要删除的对象了。返回其下标if (tempObj.title === removeTitle) {return i;}}return -1;}//给数组构造函数的原型添加方法(通过指定元素的标题删除)Array.prototype.removeObj = function (removeTitle) {var idx = this.myIndexOf(removeTitle);if (idx > -1) {this.splice(idx, 1);return;}console.log("没有找到该标题的书签!");}//删除书签(通过标题删除)BookManager.prototype.removeBook = function (removeTitle) {// for (var i = 0; i < this.books.length; i++) {// if (this.books[i].title === removeTitle) {// this.books.splice(i, 1);// break;// }// }this.books.removeObj(removeTitle);}//修改书签(通过标题去修改网址)BookManager.prototype.modifyBookUrlByTitle = function (targetTitle, modiyUrl) {//遍历书签数组,得到每一个书签对象for (var i = 0; i < this.books.length; i++) {//得到每一个书签对象var tempBook = this.books[i];//找到要修改的title书签对象if (tempBook.title === targetTitle) {//找到后,修改该书签的urltempBook.url = modiyUrl;return;}}console.log("没找到您要修改的书签!");}/************ 以上是构造函数相关 ************///创建一个书签管理器对象var bookManager = new BookManager();//创建一堆书签对象var book1 = new Book("www.baidu.com", "百度", 4);var book2 = new Book("www.tencent.com", "腾讯", 5);var book3 = new Book("www.163.com", "网易", 2);var book4 = new Book("www.baidu.com", "必读", 3);var book5 = new Book("www.sina.com", "百度", 1);//添加书签bookManager.addBook(book1);//添加书签bookManager.addBook(book2);//添加书签bookManager.addBook(book3);//添加书签bookManager.addBook(book4);//添加书签bookManager.addBook(book5);//显示所有书签信息bookManager.showAllBookInfo();//删除书签bookManager.removeBook("腾讯");//打印分隔符console.log("===================");//显示所有书签信息bookManager.showAllBookInfo();//修改书签(通过标题修改网址)bookManager.modifyBookUrlByTitle("网易", "www.126.com");//打印分隔符console.log("===================");//显示所有书签信息bookManager.showAllBookInfo();//修改书签(通过标题修改网址)bookManager.modifyBookUrlByTitle("网易2", "www.120.com");//打印分隔符console.log("===================");//显示所有书签信息bookManager.showAllBookInfo();</script></body></html>
{"ListContents" : [{"GroupCount" : "2","GroupInfo" : [{"BrandID" : "1","MainBrandName" : "奥迪","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/1.png"},{"BrandID" : "57","MainBrandName" : "阿斯顿·马丁","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/57.png"}],"PinYin" : "A"},{"GroupCount" : "16","GroupInfo" : [{"BrandID" : "58","MainBrandName" : "保时捷","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/58.png"},{"BrandID" : "59","MainBrandName" : "宾利","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/59.png"},{"BrandID" : "2","MainBrandName" : "北汽制造","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/2.png"},{"BrandID" : "3","MainBrandName" : "奔驰","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/3.png"},{"BrandID" : "4","MainBrandName" : "宝马","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/4.png"},{"BrandID" : "5","MainBrandName" : "别克","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/5.png"},{"BrandID" : "6","MainBrandName" : "比亚迪","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/6.png"},{"BrandID" : "21","MainBrandName" : "本田","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/21.png"},{"BrandID" : "37","MainBrandName" : "标致","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/37.png"},{"BrandID" : "107","MainBrandName" : "奔腾","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/107.png"},{"BrandID" : "122","MainBrandName" : "宝骏","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/122.png"},{"BrandID" : "138","MainBrandName" : "巴博斯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/138.png"},{"BrandID" : "135","MainBrandName" : "北京汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/135.png"},{"BrandID" : "150","MainBrandName" : "北汽幻速","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/150.png"},{"BrandID" : "153","MainBrandName" : "北汽威旺","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/153.png"},{"BrandID" : "156","MainBrandName" : "北汽新能源","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/156.png"}],"PinYin" : "B"},{"GroupCount" : "4","GroupInfo" : [{"BrandID" : "116","MainBrandName" : "长安汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/116.png"},{"BrandID" : "7","MainBrandName" : "长安商用","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/7.png"},{"BrandID" : "8","MainBrandName" : "长城","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/8.png"},{"BrandID" : "10","MainBrandName" : "昌河","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/10.png"}],"PinYin" : "C"},{"GroupCount" : "10","GroupInfo" : [{"BrandID" : "14","MainBrandName" : "东风风行","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/14.png"},{"BrandID" : "44","MainBrandName" : "东南","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/44.png"},{"BrandID" : "61","MainBrandName" : "道奇","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/61.png"},{"BrandID" : "47","MainBrandName" : "大众","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/47.png"},{"BrandID" : "93","MainBrandName" : "大迪","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/93.png"},{"BrandID" : "117","MainBrandName" : "东风小康","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/117.png"},{"BrandID" : "114","MainBrandName" : "东风风神","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/114.png"},{"BrandID" : "146","MainBrandName" : "东风风度","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/146.png"},{"BrandID" : "140","MainBrandName" : "DS","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/140.png"},{"BrandID" : "141","MainBrandName" : "东风御风","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/141.png"}],"PinYin" : "D"},{"GroupCount" : "6","GroupInfo" : [{"BrandID" : "62","MainBrandName" : "法拉利","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/62.png"},{"BrandID" : "46","MainBrandName" : "丰田","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/46.png"},{"BrandID" : "15","MainBrandName" : "菲亚特","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/15.png"},{"BrandID" : "16","MainBrandName" : "福特","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/16.png"},{"BrandID" : "17","MainBrandName" : "福田","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/17.png"},{"BrandID" : "18","MainBrandName" : "福迪","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/18.png"}],"PinYin" : "F"},{"GroupCount" : "4","GroupInfo" : [{"BrandID" : "55","MainBrandName" : "广汽吉奥","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/55.png"},{"BrandID" : "115","MainBrandName" : "GMC","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/115.png"},{"BrandID" : "120","MainBrandName" : "广汽乘用车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/120.png"},{"BrandID" : "133","MainBrandName" : "观致","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/133.png"}],"PinYin" : "G"},{"GroupCount" : "10","GroupInfo" : [{"BrandID" : "119","MainBrandName" : "海格","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/119.png"},{"BrandID" : "104","MainBrandName" : "华泰汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/104.png"},{"BrandID" : "143","MainBrandName" : "哈弗","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/143.png"},{"BrandID" : "96","MainBrandName" : "海马","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/96.png"},{"BrandID" : "64","MainBrandName" : "悍马","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/64.png"},{"BrandID" : "22","MainBrandName" : "红旗","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/22.png"},{"BrandID" : "43","MainBrandName" : "华普","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/43.png"},{"BrandID" : "40","MainBrandName" : "黄海汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/40.png"},{"BrandID" : "41","MainBrandName" : "汇众","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/41.png"},{"BrandID" : "20","MainBrandName" : "哈飞","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/20.png"}],"PinYin" : "H"},{"GroupCount" : "8","GroupInfo" : [{"BrandID" : "25","MainBrandName" : "江淮汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/25.png"},{"BrandID" : "27","MainBrandName" : "Jeep","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/27.png"},{"BrandID" : "29","MainBrandName" : "金杯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/29.png"},{"BrandID" : "30","MainBrandName" : "江铃","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/30.png"},{"BrandID" : "19","MainBrandName" : "吉利汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/19.png"},{"BrandID" : "65","MainBrandName" : "捷豹","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/65.png"},{"BrandID" : "144","MainBrandName" : "金龙","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/144.png"},{"BrandID" : "127","MainBrandName" : "九龙汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/127.png"}],"PinYin" : "J"},{"GroupCount" : "5","GroupInfo" : [{"BrandID" : "108","MainBrandName" : "开瑞","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/108.png"},{"BrandID" : "152","MainBrandName" : "卡威","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/152.png"},{"BrandID" : "154","MainBrandName" : "凯翼","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/154.png"},{"BrandID" : "66","MainBrandName" : "凯迪拉克","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/66.png"},{"BrandID" : "67","MainBrandName" : "克莱斯勒","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/67.png"}],"PinYin" : "K"},{"GroupCount" : "12","GroupInfo" : [{"BrandID" : "68","MainBrandName" : "兰博基尼","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/68.png"},{"BrandID" : "70","MainBrandName" : "劳斯莱斯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/70.png"},{"BrandID" : "71","MainBrandName" : "雷克萨斯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/71.png"},{"BrandID" : "72","MainBrandName" : "雷诺","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/72.png"},{"BrandID" : "74","MainBrandName" : "林肯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/74.png"},{"BrandID" : "75","MainBrandName" : "路虎","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/75.png"},{"BrandID" : "90","MainBrandName" : "力帆","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/90.png"},{"BrandID" : "31","MainBrandName" : "陆风","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/31.png"},{"BrandID" : "45","MainBrandName" : "铃木","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/45.png"},{"BrandID" : "121","MainBrandName" : "理念","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/121.png"},{"BrandID" : "128","MainBrandName" : "路特斯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/128.png"},{"BrandID" : "126","MainBrandName" : "猎豹汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/126.png"}],"PinYin" : "L"},{"GroupCount" : "5","GroupInfo" : [{"BrandID" : "33","MainBrandName" : "马自达","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/33.png"},{"BrandID" : "97","MainBrandName" : "MG","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/97.png"},{"BrandID" : "77","MainBrandName" : "玛莎拉蒂","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/77.png"},{"BrandID" : "78","MainBrandName" : "迈巴赫","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/78.png"},{"BrandID" : "79","MainBrandName" : "MINI","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/79.png"}],"PinYin" : "M"},{"GroupCount" : "1","GroupInfo" : [{"BrandID" : "118","MainBrandName" : "纳智捷","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/118.png"}],"PinYin" : "N"},{"GroupCount" : "3","GroupInfo" : [{"BrandID" : "131","MainBrandName" : "欧朗","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/131.png"},{"BrandID" : "80","MainBrandName" : "欧宝","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/80.png"},{"BrandID" : "92","MainBrandName" : "讴歌","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/92.png"}],"PinYin" : "O"},{"GroupCount" : "4","GroupInfo" : [{"BrandID" : "32","MainBrandName" : "起亚","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/32.png"},{"BrandID" : "11","MainBrandName" : "奇瑞","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/11.png"},{"BrandID" : "130","MainBrandName" : "启辰","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/130.png"},{"BrandID" : "102","MainBrandName" : "青年莲花","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/102.png"}],"PinYin" : "Q"},{"GroupCount" : "3","GroupInfo" : [{"BrandID" : "109","MainBrandName" : "瑞麒","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/109.png"},{"BrandID" : "36","MainBrandName" : "日产","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/36.png"},{"BrandID" : "94","MainBrandName" : "荣威","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/94.png"}],"PinYin" : "R"},{"GroupCount" : "12","GroupInfo" : [{"BrandID" : "95","MainBrandName" : "smart","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/95.png"},{"BrandID" : "98","MainBrandName" : "世爵","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/98.png"},{"BrandID" : "82","MainBrandName" : "萨博","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/82.png"},{"BrandID" : "83","MainBrandName" : "双龙","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/83.png"},{"BrandID" : "84","MainBrandName" : "斯巴鲁","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/84.png"},{"BrandID" : "85","MainBrandName" : "斯柯达","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/85.png"},{"BrandID" : "34","MainBrandName" : "三菱","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/34.png"},{"BrandID" : "42","MainBrandName" : "双环","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/42.png"},{"BrandID" : "123","MainBrandName" : "陕汽通家","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/123.png"},{"BrandID" : "145","MainBrandName" : "上汽大通","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/145.png"},{"BrandID" : "136","MainBrandName" : "思铭","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/136.png"},{"BrandID" : "148","MainBrandName" : "绅宝","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/148.png"}],"PinYin" : "S"},{"GroupCount" : "2","GroupInfo" : [{"BrandID" : "149","MainBrandName" : "特斯拉","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/149.png"},{"BrandID" : "147","MainBrandName" : "腾势","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/147.png"}],"PinYin" : "T"},{"GroupCount" : "6","GroupInfo" : [{"BrandID" : "110","MainBrandName" : "威麟","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/110.png"},{"BrandID" : "103","MainBrandName" : "威兹曼","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/103.png"},{"BrandID" : "151","MainBrandName" : "潍柴","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/151.png"},{"BrandID" : "86","MainBrandName" : "沃尔沃","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/86.png"},{"BrandID" : "54","MainBrandName" : "五十铃","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/54.png"},{"BrandID" : "49","MainBrandName" : "五菱","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/49.png"}],"PinYin" : "W"},{"GroupCount" : "7","GroupInfo" : [{"BrandID" : "50","MainBrandName" : "夏利","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/50.png"},{"BrandID" : "35","MainBrandName" : "新雅途","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/35.png"},{"BrandID" : "12","MainBrandName" : "雪佛兰","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/12.png"},{"BrandID" : "13","MainBrandName" : "雪铁龙","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/13.png"},{"BrandID" : "23","MainBrandName" : "现代","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/23.png"},{"BrandID" : "129","MainBrandName" : "新凯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/129.png"},{"BrandID" : "132","MainBrandName" : "西雅特","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/132.png"}],"PinYin" : "X"},{"GroupCount" : "6","GroupInfo" : [{"BrandID" : "106","MainBrandName" : "野马汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/106.png"},{"BrandID" : "24","MainBrandName" : "依维柯","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/24.png"},{"BrandID" : "53","MainBrandName" : "一汽","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/53.png"},{"BrandID" : "99","MainBrandName" : "永源汽车","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/99.png"},{"BrandID" : "101","MainBrandName" : "扬子","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/101.png"},{"BrandID" : "87","MainBrandName" : "英菲尼迪","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/87.png"}],"PinYin" : "Y"},{"GroupCount" : "4","GroupInfo" : [{"BrandID" : "91","MainBrandName" : "众泰","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/91.png"},{"BrandID" : "51","MainBrandName" : "中华","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/51.png"},{"BrandID" : "52","MainBrandName" : "中兴","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/52.png"},{"BrandID" : "105","MainBrandName" : "中誉","imgURL" : "http://www.webcars.com.cn/CarsPhoto/Brands/0/105.png"}],"PinYin" : "Z"}],"ListCount" : "130"}
{"城市代码" : [{"市" : [{"市名" : "北京","编码" : "101010100"},{"市名" : "朝阳","编码" : "101010300"},{"市名" : "顺义","编码" : "101010400"},{"市名" : "怀柔","编码" : "101010500"},{"市名" : "通州","编码" : "101010600"},{"市名" : "昌平","编码" : "101010700"},{"市名" : "延庆","编码" : "101010800"},{"市名" : "丰台","编码" : "101010900"},{"市名" : "石景山","编码" : "101011000"},{"市名" : "大兴","编码" : "101011100"},{"市名" : "房山","编码" : "101011200"},{"市名" : "密云","编码" : "101011300"},{"市名" : "门头沟","编码" : "101011400"},{"市名" : "平谷","编码" : "101011500"},{"市名" : "八达岭","编码" : "101011600"},{"市名" : "佛爷顶","编码" : "101011700"},{"市名" : "汤河口","编码" : "101011800"},{"市名" : "密云上甸子","编码" : "101011900"},{"市名" : "斋堂","编码" : "101012000"},{"市名" : "霞云岭","编码" : "101012100"},{"市名" : "北京城区","编码" : "101012200"},{"市名" : "海淀","编码" : "101010200"}],"省" : "北京"},{"市" : [{"市名" : "天津","编码" : "101030100"},{"市名" : "宝坻","编码" : "101030300"},{"市名" : "东丽","编码" : "101030400"},{"市名" : "西青","编码" : "101030500"},{"市名" : "北辰","编码" : "101030600"},{"市名" : "蓟县","编码" : "101031400"},{"市名" : "汉沽","编码" : "101030800"},{"市名" : "静海","编码" : "101030900"},{"市名" : "津南","编码" : "101031000"},{"市名" : "塘沽","编码" : "101031100"},{"市名" : "大港","编码" : "101031200"},{"市名" : "武清","编码" : "101030200"},{"市名" : "宁河","编码" : "101030700"}],"省" : "天津市"},{"市" : [{"市名" : "上海","编码" : "101020100"},{"市名" : "宝山","编码" : "101020300"},{"市名" : "嘉定","编码" : "101020500"},{"市名" : "南汇","编码" : "101020600"},{"市名" : "浦东","编码" : "101021300"},{"市名" : "青浦","编码" : "101020800"},{"市名" : "松江","编码" : "101020900"},{"市名" : "奉贤","编码" : "101021000"},{"市名" : "崇明","编码" : "101021100"},{"市名" : "徐家汇","编码" : "101021200"},{"市名" : "闵行","编码" : "101020200"},{"市名" : "金山","编码" : "101020700"}],"省" : "上海"},{"市" : [{"市名" : "石家庄","编码" : "101090101"},{"市名" : "张家口","编码" : "101090301"},{"市名" : "承德","编码" : "101090402"},{"市名" : "唐山","编码" : "101090501"},{"市名" : "秦皇岛","编码" : "101091101"},{"市名" : "沧州","编码" : "101090701"},{"市名" : "衡水","编码" : "101090801"},{"市名" : "邢台","编码" : "101090901"},{"市名" : "邯郸","编码" : "101091001"},{"市名" : "保定","编码" : "101090201"},{"市名" : "廊坊","编码" : "101090601"}],"省" : "河北"},{"市" : [{"市名" : "郑州","编码" : "101180101"},{"市名" : "新乡","编码" : "101180301"},{"市名" : "许昌","编码" : "101180401"},{"市名" : "平顶山","编码" : "101180501"},{"市名" : "信阳","编码" : "101180601"},{"市名" : "南阳","编码" : "101180701"},{"市名" : "开封","编码" : "101180801"},{"市名" : "洛阳","编码" : "101180901"},{"市名" : "商丘","编码" : "101181001"},{"市名" : "焦作","编码" : "101181101"},{"市名" : "鹤壁","编码" : "101181201"},{"市名" : "濮阳","编码" : "101181301"},{"市名" : "周口","编码" : "101181401"},{"市名" : "漯河","编码" : "101181501"},{"市名" : "驻马店","编码" : "101181601"},{"市名" : "三门峡","编码" : "101181701"},{"市名" : "济源","编码" : "101181801"},{"市名" : "安阳","编码" : "101180201"}],"省" : "河南"},{"市" : [{"市名" : "合肥","编码" : "101220101"},{"市名" : "芜湖","编码" : "101220301"},{"市名" : "淮南","编码" : "101220401"},{"市名" : "马鞍山","编码" : "101220501"},{"市名" : "安庆","编码" : "101220601"},{"市名" : "宿州","编码" : "101220701"},{"市名" : "阜阳","编码" : "101220801"},{"市名" : "亳州","编码" : "101220901"},{"市名" : "黄山","编码" : "101221001"},{"市名" : "滁州","编码" : "101221101"},{"市名" : "淮北","编码" : "101221201"},{"市名" : "铜陵","编码" : "101221301"},{"市名" : "宣城","编码" : "101221401"},{"市名" : "六安","编码" : "101221501"},{"市名" : "巢湖","编码" : "101221601"},{"市名" : "池州","编码" : "101221701"},{"市名" : "蚌埠","编码" : "101220201"}],"省" : "安徽"},{"市" : [{"市名" : "杭州","编码" : "101210101"},{"市名" : "舟山","编码" : "101211101"},{"市名" : "湖州","编码" : "101210201"},{"市名" : "嘉兴","编码" : "101210301"},{"市名" : "金华","编码" : "101210901"},{"市名" : "绍兴","编码" : "101210501"},{"市名" : "台州","编码" : "101210601"},{"市名" : "温州","编码" : "101210701"},{"市名" : "丽水","编码" : "101210801"},{"市名" : "衢州","编码" : "101211001"},{"市名" : "宁波","编码" : "101210401"}],"省" : "浙江"},{"市" : [{"市名" : "重庆","编码" : "101040100"},{"市名" : "合川","编码" : "101040300"},{"市名" : "南川","编码" : "101040400"},{"市名" : "江津","编码" : "101040500"},{"市名" : "万盛","编码" : "101040600"},{"市名" : "渝北","编码" : "101040700"},{"市名" : "北碚","编码" : "101040800"},{"市名" : "巴南","编码" : "101040900"},{"市名" : "长寿","编码" : "101041000"},{"市名" : "黔江","编码" : "101041100"},{"市名" : "万州天城","编码" : "101041200"},{"市名" : "万州龙宝","编码" : "101041300"},{"市名" : "涪陵","编码" : "101041400"},{"市名" : "开县","编码" : "101041500"},{"市名" : "城口","编码" : "101041600"},{"市名" : "云阳","编码" : "101041700"},{"市名" : "巫溪","编码" : "101041800"},{"市名" : "奉节","编码" : "101041900"},{"市名" : "巫山","编码" : "101042000"},{"市名" : "潼南","编码" : "101042100"},{"市名" : "垫江","编码" : "101042200"},{"市名" : "梁平","编码" : "101042300"},{"市名" : "忠县","编码" : "101042400"},{"市名" : "石柱","编码" : "101042500"},{"市名" : "大足","编码" : "101042600"},{"市名" : "荣昌","编码" : "101042700"},{"市名" : "铜梁","编码" : "101042800"},{"市名" : "璧山","编码" : "101042900"},{"市名" : "丰都","编码" : "101043000"},{"市名" : "武隆","编码" : "101043100"},{"市名" : "彭水","编码" : "101043200"},{"市名" : "綦江","编码" : "101043300"},{"市名" : "酉阳","编码" : "101043400"},{"市名" : "秀山","编码" : "101043600"},{"市名" : "沙坪坝","编码" : "101043700"},{"市名" : "永川","编码" : "101040200"}],"省" : "重庆"},{"市" : [{"市名" : "福州","编码" : "101230101"},{"市名" : "泉州","编码" : "101230501"},{"市名" : "漳州","编码" : "101230601"},{"市名" : "龙岩","编码" : "101230701"},{"市名" : "晋江","编码" : "101230509"},{"市名" : "南平","编码" : "101230901"},{"市名" : "厦门","编码" : "101230201"},{"市名" : "宁德","编码" : "101230301"},{"市名" : "莆田","编码" : "101230401"},{"市名" : "三明","编码" : "101230801"}],"省" : "福建"},{"市" : [{"市名" : "兰州","编码" : "101160101"},{"市名" : "平凉","编码" : "101160301"},{"市名" : "庆阳","编码" : "101160401"},{"市名" : "武威","编码" : "101160501"},{"市名" : "金昌","编码" : "101160601"},{"市名" : "嘉峪关","编码" : "101161401"},{"市名" : "酒泉","编码" : "101160801"},{"市名" : "天水","编码" : "101160901"},{"市名" : "武都","编码" : "101161001"},{"市名" : "临夏","编码" : "101161101"},{"市名" : "合作","编码" : "101161201"},{"市名" : "白银","编码" : "101161301"},{"市名" : "定西","编码" : "101160201"},{"市名" : "张掖","编码" : "101160701"}],"省" : "甘肃"},{"市" : [{"市名" : "广州","编码" : "101280101"},{"市名" : "惠州","编码" : "101280301"},{"市名" : "梅州","编码" : "101280401"},{"市名" : "汕头","编码" : "101280501"},{"市名" : "深圳","编码" : "101280601"},{"市名" : "珠海","编码" : "101280701"},{"市名" : "佛山","编码" : "101280800"},{"市名" : "肇庆","编码" : "101280901"},{"市名" : "湛江","编码" : "101281001"},{"市名" : "江门","编码" : "101281101"},{"市名" : "河源","编码" : "101281201"},{"市名" : "清远","编码" : "101281301"},{"市名" : "云浮","编码" : "101281401"},{"市名" : "潮州","编码" : "101281501"},{"市名" : "东莞","编码" : "101281601"},{"市名" : "中山","编码" : "101281701"},{"市名" : "阳江","编码" : "101281801"},{"市名" : "揭阳","编码" : "101281901"},{"市名" : "茂名","编码" : "101282001"},{"市名" : "汕尾","编码" : "101282101"},{"市名" : "韶关","编码" : "101280201"}],"省" : "广东"},{"市" : [{"市名" : "南宁","编码" : "101300101"},{"市名" : "柳州","编码" : "101300301"},{"市名" : "来宾","编码" : "101300401"},{"市名" : "桂林","编码" : "101300501"},{"市名" : "梧州","编码" : "101300601"},{"市名" : "防城港","编码" : "101301401"},{"市名" : "贵港","编码" : "101300801"},{"市名" : "玉林","编码" : "101300901"},{"市名" : "百色","编码" : "101301001"},{"市名" : "钦州","编码" : "101301101"},{"市名" : "河池","编码" : "101301201"},{"市名" : "北海","编码" : "101301301"},{"市名" : "崇左","编码" : "101300201"},{"市名" : "贺州","编码" : "101300701"}],"省" : "广西"},{"市" : [{"市名" : "贵阳","编码" : "101260101"},{"市名" : "安顺","编码" : "101260301"},{"市名" : "都匀","编码" : "101260401"},{"市名" : "兴义","编码" : "101260906"},{"市名" : "铜仁","编码" : "101260601"},{"市名" : "毕节","编码" : "101260701"},{"市名" : "六盘水","编码" : "101260801"},{"市名" : "遵义","编码" : "101260201"},{"市名" : "凯里","编码" : "101260501"}],"省" : "贵州"},{"市" : [{"市名" : "昆明","编码" : "101290101"},{"市名" : "红河","编码" : "101290301"},{"市名" : "文山","编码" : "101290601"},{"市名" : "玉溪","编码" : "101290701"},{"市名" : "楚雄","编码" : "101290801"},{"市名" : "普洱","编码" : "101290901"},{"市名" : "昭通","编码" : "101291001"},{"市名" : "临沧","编码" : "101291101"},{"市名" : "怒江","编码" : "101291201"},{"市名" : "香格里拉","编码" : "101291301"},{"市名" : "丽江","编码" : "101291401"},{"市名" : "德宏","编码" : "101291501"},{"市名" : "景洪","编码" : "101291601"},{"市名" : "大理","编码" : "101290201"},{"市名" : "曲靖","编码" : "101290401"},{"市名" : "保山","编码" : "101290501"}],"省" : "云南"},{"市" : [{"市名" : "呼和浩特","编码" : "101080101"},{"市名" : "乌海","编码" : "101080301"},{"市名" : "集宁","编码" : "101080401"},{"市名" : "通辽","编码" : "101080501"},{"市名" : "阿拉善左旗","编码" : "101081201"},{"市名" : "鄂尔多斯","编码" : "101080701"},{"市名" : "临河","编码" : "101080801"},{"市名" : "锡林浩特","编码" : "101080901"},{"市名" : "呼伦贝尔","编码" : "101081000"},{"市名" : "乌兰浩特","编码" : "101081101"},{"市名" : "包头","编码" : "101080201"},{"市名" : "赤峰","编码" : "101080601"}],"省" : "内蒙古"},{"市" : [{"市名" : "南昌","编码" : "101240101"},{"市名" : "上饶","编码" : "101240301"},{"市名" : "抚州","编码" : "101240401"},{"市名" : "宜春","编码" : "101240501"},{"市名" : "鹰潭","编码" : "101241101"},{"市名" : "赣州","编码" : "101240701"},{"市名" : "景德镇","编码" : "101240801"},{"市名" : "萍乡","编码" : "101240901"},{"市名" : "新余","编码" : "101241001"},{"市名" : "九江","编码" : "101240201"},{"市名" : "吉安","编码" : "101240601"}],"省" : "江西"},{"市" : [{"市名" : "武汉","编码" : "101200101"},{"市名" : "黄冈","编码" : "101200501"},{"市名" : "荆州","编码" : "101200801"},{"市名" : "宜昌","编码" : "101200901"},{"市名" : "恩施","编码" : "101201001"},{"市名" : "十堰","编码" : "101201101"},{"市名" : "神农架","编码" : "101201201"},{"市名" : "随州","编码" : "101201301"},{"市名" : "荆门","编码" : "101201401"},{"市名" : "天门","编码" : "101201501"},{"市名" : "仙桃","编码" : "101201601"},{"市名" : "潜江","编码" : "101201701"},{"市名" : "襄樊","编码" : "101200201"},{"市名" : "鄂州","编码" : "101200301"},{"市名" : "孝感","编码" : "101200401"},{"市名" : "黄石","编码" : "101200601"},{"市名" : "咸宁","编码" : "101200701"}],"省" : "湖北"},{"市" : [{"市名" : "成都","编码" : "101270101"},{"市名" : "自贡","编码" : "101270301"},{"市名" : "绵阳","编码" : "101270401"},{"市名" : "南充","编码" : "101270501"},{"市名" : "达州","编码" : "101270601"},{"市名" : "遂宁","编码" : "101270701"},{"市名" : "广安","编码" : "101270801"},{"市名" : "巴中","编码" : "101270901"},{"市名" : "泸州","编码" : "101271001"},{"市名" : "宜宾","编码" : "101271101"},{"市名" : "内江","编码" : "101271201"},{"市名" : "资阳","编码" : "101271301"},{"市名" : "乐山","编码" : "101271401"},{"市名" : "眉山","编码" : "101271501"},{"市名" : "凉山","编码" : "101271601"},{"市名" : "雅安","编码" : "101271701"},{"市名" : "甘孜","编码" : "101271801"},{"市名" : "阿坝","编码" : "101271901"},{"市名" : "德阳","编码" : "101272001"},{"市名" : "广元","编码" : "101272101"},{"市名" : "攀枝花","编码" : "101270201"}],"省" : "四川"},{"市" : [{"市名" : "银川","编码" : "101170101"},{"市名" : "中卫","编码" : "101170501"},{"市名" : "固原","编码" : "101170401"},{"市名" : "石嘴山","编码" : "101170201"},{"市名" : "吴忠","编码" : "101170301"}],"省" : "宁夏"},{"市" : [{"市名" : "西宁","编码" : "101150101"},{"市名" : "黄南","编码" : "101150301"},{"市名" : "海北","编码" : "101150801"},{"市名" : "果洛","编码" : "101150501"},{"市名" : "玉树","编码" : "101150601"},{"市名" : "海西","编码" : "101150701"},{"市名" : "海东","编码" : "101150201"},{"市名" : "海南","编码" : "101150401"}],"省" : "青海省"},{"市" : [{"市名" : "济南","编码" : "101120101"},{"市名" : "潍坊","编码" : "101120601"},{"市名" : "临沂","编码" : "101120901"},{"市名" : "菏泽","编码" : "101121001"},{"市名" : "滨州","编码" : "101121101"},{"市名" : "东营","编码" : "101121201"},{"市名" : "威海","编码" : "101121301"},{"市名" : "枣庄","编码" : "101121401"},{"市名" : "日照","编码" : "101121501"},{"市名" : "莱芜","编码" : "101121601"},{"市名" : "聊城","编码" : "101121701"},{"市名" : "青岛","编码" : "101120201"},{"市名" : "淄博","编码" : "101120301"},{"市名" : "德州","编码" : "101120401"},{"市名" : "烟台","编码" : "101120501"},{"市名" : "济宁","编码" : "101120701"},{"市名" : "泰安","编码" : "101120801"}],"省" : "山东"},{"市" : [{"市名" : "西安","编码" : "101110101"},{"市名" : "延安","编码" : "101110300"},{"市名" : "榆林","编码" : "101110401"},{"市名" : "铜川","编码" : "101111001"},{"市名" : "商洛","编码" : "101110601"},{"市名" : "安康","编码" : "101110701"},{"市名" : "汉中","编码" : "101110801"},{"市名" : "宝鸡","编码" : "101110901"},{"市名" : "咸阳","编码" : "101110200"},{"市名" : "渭南","编码" : "101110501"}],"省" : "陕西省"},{"市" : [{"市名" : "太原","编码" : "101100101"},{"市名" : "临汾","编码" : "101100701"},{"市名" : "运城","编码" : "101100801"},{"市名" : "朔州","编码" : "101100901"},{"市名" : "忻州","编码" : "101101001"},{"市名" : "长治","编码" : "101100501"},{"市名" : "大同","编码" : "101100201"},{"市名" : "阳泉","编码" : "101100301"},{"市名" : "晋中","编码" : "101100401"},{"市名" : "晋城","编码" : "101100601"},{"市名" : "吕梁","编码" : "101101100"}],"省" : "山西"},{"市" : [{"市名" : "乌鲁木齐","编码" : "101130101"},{"市名" : "石河子","编码" : "101130301"},{"市名" : "昌吉","编码" : "101130401"},{"市名" : "吐鲁番","编码" : "101130501"},{"市名" : "库尔勒","编码" : "101130601"},{"市名" : "阿拉尔","编码" : "101130701"},{"市名" : "阿克苏","编码" : "101130801"},{"市名" : "喀什","编码" : "101130901"},{"市名" : "伊宁","编码" : "101131001"},{"市名" : "塔城","编码" : "101131101"},{"市名" : "哈密","编码" : "101131201"},{"市名" : "和田","编码" : "101131301"},{"市名" : "阿勒泰","编码" : "101131401"},{"市名" : "阿图什","编码" : "101131501"},{"市名" : "博乐","编码" : "101131601"},{"市名" : "克拉玛依","编码" : "101130201"}],"省" : "新疆"},{"市" : [{"市名" : "拉萨","编码" : "101140101"},{"市名" : "山南","编码" : "101140301"},{"市名" : "阿里","编码" : "101140701"},{"市名" : "昌都","编码" : "101140501"},{"市名" : "那曲","编码" : "101140601"},{"市名" : "日喀则","编码" : "101140201"},{"市名" : "林芝","编码" : "101140401"}],"省" : "西藏"},{"市" : [{"市名" : "台北县","编码" : "101340101"},{"市名" : "高雄","编码" : "101340201"},{"市名" : "台中","编码" : "101340401"}],"省" : "台湾"},{"市" : [{"市名" : "海口","编码" : "101310101"},{"市名" : "三亚","编码" : "101310201"},{"市名" : "东方","编码" : "101310202"},{"市名" : "临高","编码" : "101310203"},{"市名" : "澄迈","编码" : "101310204"},{"市名" : "儋州","编码" : "101310205"},{"市名" : "昌江","编码" : "101310206"},{"市名" : "白沙","编码" : "101310207"},{"市名" : "琼中","编码" : "101310208"},{"市名" : "定安","编码" : "101310209"},{"市名" : "屯昌","编码" : "101310210"},{"市名" : "琼海","编码" : "101310211"},{"市名" : "文昌","编码" : "101310212"},{"市名" : "保亭","编码" : "101310214"},{"市名" : "万宁","编码" : "101310215"},{"市名" : "陵水","编码" : "101310216"},{"市名" : "西沙","编码" : "101310217"},{"市名" : "南沙岛","编码" : "101310220"},{"市名" : "乐东","编码" : "101310221"},{"市名" : "五指山","编码" : "101310222"},{"市名" : "琼山","编码" : "101310102"}],"省" : "海南省"},{"市" : [{"市名" : "长沙","编码" : "101250101"},{"市名" : "株洲","编码" : "101250301"},{"市名" : "衡阳","编码" : "101250401"},{"市名" : "郴州","编码" : "101250501"},{"市名" : "常德","编码" : "101250601"},{"市名" : "益阳","编码" : "101250700"},{"市名" : "娄底","编码" : "101250801"},{"市名" : "邵阳","编码" : "101250901"},{"市名" : "岳阳","编码" : "101251001"},{"市名" : "张家界","编码" : "101251101"},{"市名" : "怀化","编码" : "101251201"},{"市名" : "黔阳","编码" : "101251301"},{"市名" : "永州","编码" : "101251401"},{"市名" : "吉首","编码" : "101251501"},{"市名" : "湘潭","编码" : "101250201"}],"省" : "湖南"},{"市" : [{"市名" : "南京","编码" : "101190101"},{"市名" : "镇江","编码" : "101190301"},{"市名" : "苏州","编码" : "101190401"},{"市名" : "南通","编码" : "101190501"},{"市名" : "扬州","编码" : "101190601"},{"市名" : "宿迁","编码" : "101191301"},{"市名" : "徐州","编码" : "101190801"},{"市名" : "淮安","编码" : "101190901"},{"市名" : "连云港","编码" : "101191001"},{"市名" : "常州","编码" : "101191101"},{"市名" : "泰州","编码" : "101191201"},{"市名" : "无锡","编码" : "101190201"},{"市名" : "盐城","编码" : "101190701"}],"省" : "江苏"},{"市" : [{"市名" : "哈尔滨","编码" : "101050101"},{"市名" : "牡丹江","编码" : "101050301"},{"市名" : "佳木斯","编码" : "101050401"},{"市名" : "绥化","编码" : "101050501"},{"市名" : "黑河","编码" : "101050601"},{"市名" : "双鸭山","编码" : "101051301"},{"市名" : "伊春","编码" : "101050801"},{"市名" : "大庆","编码" : "101050901"},{"市名" : "七台河","编码" : "101051002"},{"市名" : "鸡西","编码" : "101051101"},{"市名" : "鹤岗","编码" : "101051201"},{"市名" : "齐齐哈尔","编码" : "101050201"},{"市名" : "大兴安岭","编码" : "101050701"}],"省" : "黑龙江"},{"市" : [{"市名" : "长春","编码" : "101060101"},{"市名" : "延吉","编码" : "101060301"},{"市名" : "四平","编码" : "101060401"},{"市名" : "白山","编码" : "101060901"},{"市名" : "白城","编码" : "101060601"},{"市名" : "辽源","编码" : "101060701"},{"市名" : "松原","编码" : "101060801"},{"市名" : "吉林","编码" : "101060201"},{"市名" : "通化","编码" : "101060501"}],"省" : "吉林"},{"市" : [{"市名" : "沈阳","编码" : "101070101"},{"市名" : "鞍山","编码" : "101070301"},{"市名" : "抚顺","编码" : "101070401"},{"市名" : "本溪","编码" : "101070501"},{"市名" : "丹东","编码" : "101070601"},{"市名" : "葫芦岛","编码" : "101071401"},{"市名" : "营口","编码" : "101070801"},{"市名" : "阜新","编码" : "101070901"},{"市名" : "辽阳","编码" : "101071001"},{"市名" : "铁岭","编码" : "101071101"},{"市名" : "朝阳","编码" : "101071201"},{"市名" : "盘锦","编码" : "101071301"},{"市名" : "大连","编码" : "101070201"},{"市名" : "锦州","编码" : "101070701"}],"省" : "辽宁"}]}
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>作业</title></head><body><script type="text/javascript">//根据city.json 手动写一个JS字面量对象,并且封装到数据模型中var rootObj = {//省份数组provinces : [//每个省份对象{provinceName : "黑龙江省",//城市数组cities : [//每个城市对象{cityName : "哈尔滨市",cityCode : "1001"},{cityName : "大庆市",cityCode : "1002"},{cityName : "鸡西市",cityCode : "1003"}]},{provinceName : "河北省",cities : [{cityName : "石家庄",cityCode : "2001"},{cityName : "廊坊市",cityCode : "2002"}]}]}//省份构造函数function Province (provinceName) {this.provinceName = provinceName;//城市数组this.cities = new Array();}//城市构造函数function City (cityName, cityCode) {this.cityName = cityName;this.cityCode = cityCode;}//存储省份对象的数组var provinceArray = new Array();//解析字面量对象、并且封装数据模型//获得省份数组var provinces = rootObj.provinces;//遍历省份数组for (var tempProvinceIdx in provinces) {//得到每一个省份对象var tempProvince = provinces[tempProvinceIdx];/** 创建省份对象(构造函数) **/var tempProvinceObj = new Province(tempProvince.provinceName);/** 把省份对象添加到省份数组中 **/provinceArray.push(tempProvinceObj);//获得城市数组var cities = tempProvince.cities;//遍历城市数组for (var tempCityIdx in cities) {//得到每一个城市对象var tempCity = cities[tempCityIdx];/** 创建城市对象(构造函数) **/var tempCityObj = new City(tempCity.cityName, tempCity.cityCode);/** 把每个城市对象添加到当前省的城市数组中 **/tempProvinceObj.cities.push(tempCityObj);// 遍历城市对象for (var tempCityProperty in tempCity) {//找某个城市if (tempCityProperty === 'cityName') {//获得城市名字var cityName = tempCity[tempCityProperty];if (cityName === '石家庄') {//格式化输出console.log(" \n 省份:" + tempProvince.provinceName + " \n 城市:" + tempCity.cityName + " \n 编码:" + tempCity.cityCode);}}}}}console.log(provinceArray);</script></body></html>
/** 封装ajax* method: 请求方式 GET/POST* url: 请求路径* data: 参数* successCallBackFn: 响应成功回调函数* failCallBackFn: 响应失败回调函数*/function ajaxFn (method, url, data, successCallBackFn, failCallBackFn) {var xhr;//创建请求对象if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else if (window.ActiveXObject) {var versions = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];for (var i = 0; i < versions.length; i++) {try {xhr = new ActiveXObject(versions[i]);break;} catch (e) {console.log(e);}}} else {//创建一个错误对象//throw 是主动抛出一个异常错误throw new Error("浏览器不支持AJAX");}//打开链接 和 发送请求if (method == "GET" || method == "get") {//利用ajax GET请求会有缓存,为了避免每次访问的路径不一样。我们可以在//url后面加上 Math.random()来解决。xhr.open(method, url + "?" + data + Math.random(), true);xhr.send(null);} else if (method == "POST" || method == "post") {xhr.open(method, url, true);//post请求需要设置请求头xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");xhr.send(data);} else {console.log("请求方式不对!");}//请求响应结果xhr.onreadystatechange = function () {if (xhr.readyState == 4 ) {if (xhr.status == 200) {//回调成功的函数successCallBackFn(xhr.responseText);} else {//失败failCallBackFn("失败!");}}}return xhr;}
/** 事件封装工具*/var EventUtil = {//添加事件的方法/** element: 给"谁"(某个元素)添加事件* eventType: 事件类型* handler: 具体实现函数*/addHandler : function (element, eventType, handler) {//三种实现if (window.addEventListener) {//IE9及IE9以上element.addEventListener(eventType, handler);} else if (window.attachEvent) {//IE8及IE8以下实现//attachEvent需要的事件类型 需要 加上 onelement.attachEvent("on" + eventType, handler);} else {//通过中括号访问属性的语法才可以element["on" + eventType] = handler;}},removeHandler : function (element, eventType, handler) {if (window.removeEventListener) {element.removeEventListener(eventType, handler);} else if (window.detachEvent) {element.detachEvent("on" + eventType, handler);} else {element["on" + eventType] = null;}}}
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>解析carJson</title><script type="text/javascript" src="js/AjaxUtil.js" ></script><script type="text/javascript" src="js/EventUtil.js" ></script></head><body><script type="text/javascript">//通过工具类,给window添加onload事件EventUtil.addHandler(window, "load", function () {// alert($("load_btn").value);//执行完onload事件后,给button添加单击事件EventUtil.addHandler($("load_btn"), "click", function () {//点击按钮通过ajax来异步加载数据// ajaxFn("GET", "car.json", null, function () {// 可以这么写 这个是成功// }, function () {// 这个是失败// });//调用ajax异步请求数据ajaxFn("GET", "car.json", null, successCallBackFn,failCallBackFn);});});//ajax返回的成功函数function successCallBackFn (returnValue) {// console.log(returnValue);//把JSON字符串转换成JS对象var rootObj = JSON.parse(returnValue);// console.log(rootObj);//得到listContents数组var listContentArray = rootObj.ListContents;//获得外层tablevar outTable = $("out_table");//遍历listContentArrayfor (var tempListContentIdx in listContentArray) {//得到每一个listContent对象var tempListContent = listContentArray[tempListContentIdx];//创建外层trvar outTr = createElement("tr");//创建外层tdvar outTd = createElement("td");//创建内层tablevar inTable = createElement("table");//创建内层theadvar inThead = createElement("thead");//创建内层thead的textNodevar inTheadValue = createTextNode(tempListContent.PinYin);//添加textNodeinThead.appendChild(inTheadValue);//添加inTheadinTable.appendChild(inThead);//添加inTableoutTd.appendChild(inTable);//添加outTdoutTr.appendChild(outTd);//添加outTroutTable.appendChild(outTr);/******** 创建内部的tr 和 td *******///得到carArray数组var carArray = tempListContent.GroupInfo;//遍历carArrayfor (var tempCarIdx in carArray) {//得到每一个car对象var tempCar = carArray[tempCarIdx];//创建内部trvar inTr = createElement("tr");//创建内部tdvar inTd = createElement("td");//创建内部td的textNodevar inTdValue = createTextNode(tempCar.MainBrandName);//添加textNodeinTd.appendChild(inTdValue);//添加inTdinTr.appendChild(inTd);//添加inTrinTable.appendChild(inTr);}}}//ajax返回的失败函数function failCallBackFn (returnValue) {alert(returnValue);}//封装一下通过id获取标签元素function $ (idValue) {return document.getElementById(idValue);}//封装一下创建元素的方法function createElement (elementName) {return document.createElement(elementName);}//封装一下创建textNodefunction createTextNode (elementValue) {return document.createTextNode(elementValue);}</script><input type="button" value="加载数据" id="load_btn"/><br /><br /><table id="out_table" border="1px" ><!--<tr><td><table><thead>A</thead><tr><td>阿拉斯加</td></tr><tr><td>阿拉丁</td></tr></table></td></tr><tr><td><table><thead>B</thead><tr><td>宝马</td></tr><tr><td>奔驰</td></tr></table></td></tr>--></table></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>选人</title><style type="text/css">div {float: left;border: 1px solid red;}#main_div {width: 500px;height: 300px;margin-left: 300px;}#left_div {width: 200px;height: 300px;}#center_div {width: 94px;height: 300px;text-align: center;}#right_div {width: 200px;height: 300px;float: right;}#left_sel {width: 200px;height: 280px;}#right_sel {width: 200px;height: 280px;}input {margin-top: 30px;}</style><!-- 导入事件工具js文件 --><script type="text/javascript" src="EventUtil.js"></script></head><body><div id="main_div"><!-- 左边的div --><div id="left_div"><label id="left_label">0</label><select id="left_sel" multiple></select></div><!-- 中间的div --><div id="center_div"><input type="button" value="添加" id="add_btn" /><br /><input type="button" value="移除" id="remove_btn" /><br /><input type="button" value="全部添加" id="addAll_btn" /><br /><input type="button" value="全部移除" id="removeAll_btn" /></div><!-- 右边的div --><div id="right_div"><label id="right_label">0</label><select id="right_sel" multiple></select></div></div><script type="text/javascript">//左边selvar leftSel = $("left_sel");//左边数据数组var leftPersonArray = new Array();//右边selvar rightSel = $("right_sel");//右边数据数组var rightPersonArray = new Array();//window的onload事件EventUtil.addHandler(window, "load", function () {//1、初始化数据var personObj = [{name : "张三"},{name : "李四"},{name : "王五"},{name : "赵六"},{name : "冯七"}];//遍历personObjfor (var tempIdx in personObj) {//得到每个person对象var tempPerson = personObj[tempIdx];//添加到左边数据数组leftPersonArray.push(tempPerson);//重置左边selresetSel(leftSel, tempPerson.name);//人数leftAndRightCount();}//2、给左边sel添加事件EventUtil.addHandler(leftSel, "dblclick", function () {//添加右边数据数组// this.selectedIndex 相当于leftSel.selectedIndex,获得选中option的下标rightPersonArray.push(leftPersonArray[this.selectedIndex]);//重置右边selresetSel(rightSel, leftPersonArray[this.selectedIndex].name);//删除左边数据数组leftPersonArray.splice(this.selectedIndex, 1);//删除左边option//this.options 获得所有option 是一个数组leftSel.removeChild(this.options[this.selectedIndex]);//人数leftAndRightCount();});//3、给添加按钮添加事件EventUtil.addHandler($("add_btn"), "click", function () {//遍历optionsfor (var i = 0; i < leftSel.options.length; i++) {//找出选中的optionif (leftSel.options[i].selected) {//添加右边数据数组rightPersonArray.push(leftPersonArray[i]);//重置右边sel的方法resetSel(rightSel, leftPersonArray[i].name);//删除左边数据数组leftPersonArray.splice(i, 1);//删除左边的optionleftSel.removeChild(leftSel.options[i]);//每次删除后要改变下标// i -= 1;i--;}}//人数leftAndRightCount();});//4、右边sel添加事件//5、给移除按钮添加事件//6、给全部添加按钮添加事件EventUtil.addHandler($("addAll_btn"), "click", function () {//遍历左边的optionsfor (var i = 0; i < leftSel.options.length; i++) {//添加右边数据数组rightPersonArray.push(leftPersonArray[i]);//重置右边selresetSel(rightSel, leftPersonArray[i].name);//删除左边数据数组leftPersonArray.splice(i, 1);//删除左边optionleftSel.removeChild(leftSel.options[i]);//改变下标i--;}//人数leftAndRightCount();});//7、给全部移除按钮添加事件});//封装左边和右边人数的方法function leftAndRightCount () {$("left_label").innerHTML = leftPersonArray.length;$("right_label").innerHTML = rightPersonArray.length;}//封装重置sel的方法function resetSel (sel, textNodeValue) {//创建optionvar option = createElement("option");//创建textNodevar optionValue = createTextNode(textNodeValue);//添加textNodeoption.appendChild(optionValue);//添加optionsel.appendChild(option);}//封装创建元素的方法function createElement (elementName) {return document.createElement(elementName);}//封装创建textNode的方法function createTextNode (elementValue) {return document.createTextNode(elementValue);}//封装通过id获取标签的方法function $ (idName) {return document.getElementById(idName);}</script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>页面1</title><script type="text/javascript">window.onload = function () {var oBtn = document.getElementById('btn1');oBtn.onclick = function () {window.open("open跨窗口传值2.html","123",'height=400,width=400,top=100,left=200,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');var content1 = document.getElementById('input1').value;}}</script></head><body><input type="text" id="input1"><button id="btn1">点击</button></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>页面2</title><script type="text/javascript">window.onload = function () {/*var oBtn = document.getElementById('btn1');oBtn.onclick = function () {window.open("open跨窗口传值2.html");var content1 = document.getElementById('input1').value;}*/var content2 = document.getElementById("input2");content2.value= window.opener.document.getElementById('input1').value// 传回var oBtn = document.getElementById('btn2');oBtn.onclick = function () {window.opener.document.getElementById('input1').value = content2.value;}}</script></head><body><input type="text" id="input2"><button id="btn2">点击</button></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>代理设计模式</title></head><body><script type="text/javascript">/*小明喜欢小红,想给小红送一朵花,但小明不好意思直接送,委托小红的闺蜜小兰去送。最后小红接收到花。*/// function Flower () {// }//构造函数var Flower = function (name) {this.name = name;}//小明var xiaoming = {sendFlower : function (target) {var flower = new Flower("菊花");//送给委托人小兰(最终通过委托人在送给小红)target.receive(flower);}}//小红var xiaohong = {//最后接花的人receive : function (flower) {console.log("接收到 " + flower.name + "了,好开心!");}}//小兰var xiaolan = {//接收花的方法,刚接完就送给小红receive : function (flower) {//给小红xiaohong.receive(flower);}}//小明送花xiaoming.sendFlower(xiaolan);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>单例设计模式</title></head><body><script type="text/javascript">//人的构造函数var Person = function () {}//创建两个人的对象,证明是两个不同的实例var person1 = new Person();var person2 = new Person();console.log("person1 === person2:" + person1 === person2);// function fn () {// console.log("测试");// }//这种方式,声明即调用。//语法:(函数声明)();(function fn () {console.log("测试");})();//还可以这么写var fn1 = (function () {console.log("测试");})();//写一个单利var Dog = (function () {// console.log(123);console.log("==========");//通过闭包外部函数的局部变量,模拟“静态”变量,这个变量会存在内存中,每次调用外部函数的时候才初始化这个instancevar instance;//这个才是真的构造函数实现var Dog = function (name) {console.log("---------");this.name = name;//判断instance是否为空if (instance) {return instance;}//如果不存在,把当前对象赋值给instanceinstance = this;return instance;}//外部函数return一个 内部的构造函数return Dog;})();var dog1 = new Dog("妞妞");var dog2 = new Dog("憨憨");console.log("dog1 === dog2 : " + (dog1 === dog2));//注意: 打印的是妞妞,因为还没有等到这个对象生成,就返回第一次那个对象了。console.log(dog2.name);dog2.name = "打脸";console.log(dog1.name);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>策略设计模式</title></head><body><script type="text/javascript">//创建一个策略对象,方便管理相应的算法var stategaies = {a : function (salary) {return salary * 2;},b : function (salary) {return salary * 3;},c : function (salary) {return salary * 4;}}//var getMoney = function (level, salary) {//分配策略,因为是形参,通过中括号的语法调用属性,得到的是a、b、c方法,传入salary直接调用即可return stategaies[level](salary);}var money = getMoney("c", 20000);console.log(money);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>适配器设计模式01</title></head><body><script type="text/javascript">//开发调用外部接口的方式(没用适配器)var googleMap = {show : function () {console.log("显示谷歌地图数据!");}}var baiduMap = {show : function () {console.log("显示百度地图数据!");}}var renderMap = function (map) {//判断各种地图中是否有show函数if (map.show instanceof Function) {//如果有的话,就可以直接调用,显示数据map.show();}}renderMap(baiduMap);renderMap(googleMap);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>适配器设计模式02</title></head><body><script type="text/javascript">//利用适配器设计模式,解决谷歌和百度地图数据方法不兼容的问题var googleMap = {show : function () {console.log("显示谷歌地图!");}}var baiduMap = {loadData : function () {console.log("显示百度地图数据!");}}//给百度地图添加一个适配器对象var baiduAdapter = {//适配器实现一个show函数show : function () {//在这里调用百度显示数据的函数,并且把运行结果返回return baiduMap.loadData();}}var renderMap = function (map) {if (map.show instanceof Function) {map.show();}}renderMap(googleMap);// renderMap(baiduMap);//为了兼容,这里需要传入我们写的适配器对象renderMap(baiduAdapter);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>工厂设计模式</title></head><body><script type="text/javascript">//利用工厂设计模式创建对象function createPerson (name, age, sex) {var person = new Object();//动态插入了一个属性person.name = name;person.age = age;person.sex = sex;person.sayHello = function () {console.log(this.name);}return person;}var person1 = createPerson("小红", 18, "女");var person2 = createPerson("小明", 19, "男");person1.sayHello();person2.sayHello();console.log(person1 === person2);/*工厂设计模式创建对象的优缺点优点:解决了创建多个相似对象的问题。缺点:没有解决对对象的识别问题(没有明确对象的类型)。*/</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>模板设计模式</title></head><body><script type="text/javascript">/*咖啡1、烧水2、冲咖啡3、把咖啡倒入杯子4、加糖和奶*///喝咖啡的构造函数var Coffee = function () {}// function Coffee () {// }//1、烧水Coffee.prototype.boilWater = function () {console.log("烧水");}//2、冲咖啡Coffee.prototype.brewCoffee = function () {console.log("冲咖啡");}//3、把咖啡倒入杯子Coffee.prototype.pourInCup = function () {console.log("把咖啡倒入杯子");}//4、加糖、奶Coffee.prototype.addSugarAndMilk = function () {console.log("加糖和奶");}// 封装一下喝咖啡的流程Coffee.prototype.init = function () {this.boilWater();this.brewCoffee();this.pourInCup();this.addSugarAndMilk();}//创建一个咖啡对象var coffee = new Coffee();coffee.init();/*茶1、烧水2、沏茶3、把茶放入杯子中4、加柠檬*///喝茶的构造函数var Tea = function () {}//1、烧水Tea.prototype.boilWater = function () {console.log("烧水");}//2、沏茶Tea.prototype.brewTea = function () {console.log("沏茶");}//3、把茶放到杯子中Tea.prototype.pourInCup = function () {console.log("把茶放到杯子中");}//4、加柠檬Tea.prototype.addLemon = function () {console.log("加柠檬");}//封装喝茶的流程Tea.prototype.init = function () {this.boilWater();this.brewTea();this.pourInCup();this.addLemon();}Tea.prototype = new S();//创建茶的对象var tea = new Tea();tea.init();</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>模板设计模式02</title></head><body><script type="text/javascript">/*经过分析,我们可以把某些构造函数,相同的部分抽象出来,抽象到一个父类(构造函数)里,那么其他子类(构造函数)的原型对象只要指向这个父类(构造函数)的实例,就形成了一个继承关系。切记:JS中没有类的继承,只有对象的继承。换句话说,某个类型只能继承于某个类型的一个实例对象。之前写的咖啡和茶的流程,我们可以抽象出来以下几个步骤:1、烧水2、冲(饮品)名字可以叫做:brew()3、把(饮品)放到杯子中4、加(材料)名字可以叫做:addDrink()*///父类(构造函数)var SuperObj = function () {}//抽象出来的烧水方法SuperObj.prototype.boilWater = function () {//这个要实现,因为无论喝的是什么饮品,都需要烧水,它们(子类)都具备相同的烧水功能,所以在父类里实现这个方法。子类就不用实现了,直接调用即可。console.log("烧水!");}//抽象出来的冲(饮品)方法SuperObj.prototype.brew = function () {//这里什么都不用实现,让子类去实现它们想要实现的功能,//因为冲什么父类也不知道。}//抽象出来的把饮品放在杯子中SuperObj.prototype.pourInCup = function () {//这里也是什么都不用实现,因为不确定放的是什么饮品。}//抽象出来的加材料的方法SuperObj.prototype.addDrink = function () {//这里也什么都不用实现,因为不确定加的是什么材料}//抽象出来的喝饮品流程的方法SuperObj.prototype.init = function () {//要实现这个方法,因为无论是咖啡还是茶,都是以上者四个流程,//只是流程内部的实现不一样而已。this.boilWater();this.brew();this.pourInCup();this.addDrink();}//咖啡构造函数var Coffee = function () {}//建立子类和父类的关系(也就是指定一下原型对象)Coffee.prototype = new SuperObj();//父类烧水的方法可以满足当前子类,所以不用重写。//重写:重写的意思就是,重新实现一下父类的某个方法,相当于覆盖掉了父类的这个方法。重写的方法名一定要和父类你要覆盖的那个方法名一致,参数也一模一样。//重写冲饮品的方法Coffee.prototype.brew = function () {console.log("准备冲咖啡!");}//重写把饮品放到杯子中的方法Coffee.prototype.pourInCup = function () {console.log("把咖啡倒入杯子中!");}//重写加材料的方法Coffee.prototype.addDrink = function () {console.log("给咖啡加糖和牛奶!");}//创建一个咖啡对象var coffee1 = new Coffee();coffee1.init();//茶的构造函数var Tea = function () {}//子类和父类建立联系(设置原型对象)Tea.prototype = new SuperObj();//重写冲饮品的方法Tea.prototype.brew = function () {console.log("沏茶!");}//重写把饮品放到杯子中的方法Tea.prototype.pourInCup = function () {console.log("把茶倒入杯子中!");}//重写加材料的方法Tea.prototype.addDrink = function () {console.log("给茶添加柠檬!");}//创建tea对象var tea1 = new Tea();tea1.init();</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>观察者设计模式缺陷版</title></head><body><script type="text/javascript">/*场景:小明、小红等人去售楼处买房,但没有中意的房子,留了自己的联系方式给售楼处,然后将来有合适的房源后,会发短信通知小明或小红等人。发布者:售楼处订阅者:小红、小明等人- 售楼处收集或存储小红、小明等人的信息(回调函数)- 售楼处发短信通知小红、小明等人来看房。*///售楼处对象 (发布者)var saleHouse = {};//用户信息列表(订阅者)saleHouse.clientList = [];//添加用户信息的方法 (回调函数)//参数是一个回调函数saleHouse.listen = function (callBackFn) {//把函数添加到用户信息列表中this.clientList.push(callBackFn);}//通知方法saleHouse.trigger = function () {for (var i = 0; i < this.clientList.length; i++) {// this.clientList[i]();//调用函数 (就是获取信息列表里存取的回调函数,然后进行调用)this.clientList[i].apply(this, arguments);}}//调用添加用户信息方法//可以理解为这个是注册小明的用户信息saleHouse.listen(function (houseName, price) {console.log("房名:" + houseName);console.log("价格:" + price);});//在添加一个小红saleHouse.listen(function (houseName, price) {console.log("房名:" + houseName);console.log("价格:" + price);});// console.log(saleHouse.clientList); ////通知小明和小红房源信息saleHouse.trigger('英国宫', 1100000);console.log("-----------------");saleHouse.trigger('剑桥郡', 1300000);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>观察者设计模式_改进版</title></head><body><script type="text/javascript">//售楼处 发布者var saleHouse = {}//用户信息列表(Map中的值是用户信息列表,键是相应的订阅者) (订阅者)saleHouse.clientMap = new Map();//添加用户信息的方法 (回调函数)//参数是一个回调函数 (带标示)saleHouse.listen = function (key, callBackFn) {//先判断用户信息Map中是否有这个keyif (!saleHouse.clientMap.get(key)) {//如果没有当前key,则加入key并且初始化key对应的value,value是一个回调函数数组saleHouse.clientMap.set(key, []);}//把传进来的回调函数push到Map中key对应的value数组中saleHouse.clientMap.get(key).push(callBackFn);}//通知方法saleHouse.trigger = function () {//获取传进来参数数组中的第一个参数,也就是订阅者Map中的keyvar key = arguments[0];// Array.prototype.shift.call(this,arguments);//获得该标识下的回调函数数组var callBackFns = this.clientMap.get(key);//判断数组是否为空if (!callBackFns || callBackFns.length == 0) {return;}//遍历当前key下对应的value函数数组,并且调用for (var i = 0; i < callBackFns.length; i++) {callBackFns[i].call(this, arguments[1], arguments[2]);}}//调用listen方法(添加小明)saleHouse.listen('小明' ,function (houseName, price) {console.log('小明');console.log('房子:' + houseName);console.log('价格:' + price);});//调用listen方法(添加小红)saleHouse.listen('小红' ,function (houseName, price) {console.log('小红');console.log('房子:' + houseName);console.log('价格:' + price);});//调用通知方法saleHouse.trigger('小明','英国宫', 2000000);saleHouse.trigger('小明','剑桥郡', 3000000);saleHouse.trigger('小红','英国宫', 2000000);</script></body></html>
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>观察者模式最终完美版</title><script src="../../../../../jquery-2.2.3.js"></script><script>/*发布者: 售楼处订阅者: 小明小红等人开发思路:1. 售楼处存储小红,小明等人的信息(用到回调函数的概念)2. 售楼处发短信通知小明和小红来看房*//*取消订阅的功能售楼处2不能用售楼处的方法*/// 观察者设计模式通用模板对象var eventObj = {clientMap : new Map(),// 订阅方法listen : function (key, callback) {if (!this.clientMap.get(key)) {this.clientMap.set(key, []);}// callback 添加到key对应的value数组中this.clientMap.get(key).push(callback);},// 取消订阅方法remove : function (key) {if (!this.clientMap.get(key)) {alert("无此人");return;}/*数组的方法:slice是截取子数组slice(start, end)splice 是 删,改,增splice(start, length, 替换1, 替换2, 替换3,.....)split: 是字符串的方法字符串中没有splice方法*/// 方法一:// key有,value中数组为空this.clientMap.get(key).splice(0);// 方法二:// key有,value中数组为空//this.clientMap.set(key,[]);// 方法三:// 删除键和值//this.clientMap.delete(key);console.log("已经取消订阅");},// 通知方法trigger : function () {var key = arguments[0];var callbackFns = this.clientMap.get(key);if(!callbackFns || callbackFns.length === 0) {return;}for (var i = 0; i< callbackFns.length; i++) {callbackFns[i].call(this, arguments[1],arguments[2]);}// 测试console.log(callbackFns.length);}};// 复制工厂 , 调用这个方法后,对象就拥有了模板里的所有属性// 用来渲染属性var installEvent = function (obj) {// 把模板对象的指针赋值给了obj// obj 也指向了eventObj对象// obj = eventObj; // 不能直接赋值for (var tempProp in eventObj) {// obj[tempProp] 给obj添加了一个新的tempProp属性obj[tempProp] = eventObj[tempProp];}//obj['clientMap'] = new Map();obj.clientMap = new Map();};// 售楼处1var saleHouse1 = {};// 售楼处2var saleHouse2 = {};// 渲染属性installEvent(saleHouse1);installEvent(saleHouse2);// 复制过了, 售楼处已经有属性了// 添加用户信息方法// 调用listen方法 (添加小明)saleHouse1.listen('小明',function(houseName, price) {console.log('小明');console.log("房名:" +houseName);console.log("价格:" +price);});saleHouse2.listen('小明',function(houseName, price) {console.log('小明');console.log("房名:" +houseName);console.log("价格:" +price);});// 调用listen方法 (添加小红)saleHouse1.listen('小红',function(houseName, price) {console.log('小红');console.log("房名:" +houseName);console.log("价格:" +price);});saleHouse2.listen('小红',function(houseName, price) {console.log('小红');console.log("房名:" +houseName);console.log("价格:" +price);});// 小明取消订阅saleHouse1.remove("小明");// 通知// 通知小明和小红 (群发)saleHouse1.trigger('小明','英国宫_售楼处1',110000);saleHouse2.trigger('小明','英国宫_售楼处2',110000);console.log("*******");saleHouse1.trigger('小红','剑桥郡_售楼处1',130000);saleHouse2.trigger('小红','剑桥郡_售楼处2',130000);</script></head><body></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>高阶函数</title></head><body><script type="text/javascript">//高阶函数 (函数可以作为参数、函数可以赋值给变量、函数可以作为返回值)//1、事件的封装// .....//2、Ajax的封装//......//作用域安全问题//猫的构造器var Cat = function (name, type) {this.name = name;this.type = type;}//创建猫的对象var cat1 = new Cat("端午", "波斯猫");console.log(cat1.name, cat1.type);//这只是一个普通函数调用var cat2 = Cat("咪咪", "加菲猫");// console.log(cat2.name, cat2.type);//如果直接调用Cat函数的话,内部的this指针,就会根据当前运行环境改变而变成windowconsole.log(window.name, window.type);//解决上面的问题。//狗的构造函数var Dog = function (name, type) {//判断this指针的构造函数是否是Dogif (this instanceof Dog) {this.name = name;this.type = type;//返回当前对象return this;}return new Dog(name, type);}//正常通过new 关键字创建狗的对象var dog1 = new Dog("妞妞", "萨摩耶");console.log(dog1.name, dog1.type);//直接调用Dog() 创建狗的对象var dog2 = Dog("八公", "秋田犬");console.log(dog2.name, dog2.type);console.log(window.name, window.type);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>柯里化</title></head><body><script type="text/javascript">//全局变量实现叠加功能//声明全局变量var totalCount = 0;var fn = function (count) {totalCount += count;}//每次调用fnfn(100);fn(200);fn(300);console.log(totalCount);//利用柯里化可以实现,把每次执行函数的结果存储起来,当你最后想得到结果的时候在停止存储。var fn2 = (function () {//把每次调用内部函数的结果都存在这个数组中,因为是闭包,这个数组不会被销毁,存在内存中。var args = [];return function () {//当没有参数传入的时候,停止,得到最后的结果if (!arguments.length) {//!arguments.length 和 arguments.length == 0 是一个意思var returnNum = 0;//遍历args取出每个结果,叠加起来,返回。for (var i = 0; i < args.length; i++) {returnNum += args[i];}return returnNum;}//把每次传进来的数值存储到args数组中// args.push(arguments[0]);[].push.apply(args, arguments);}})();fn2(100);fn2(300);fn2(600);//当函数没有传入任何参数的时候停止。得到最后的结果。console.log(fn2());</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>柯里化</title></head><body><script type="text/javascript">//全局变量实现叠加功能//声明全局变量var totalCount = 0;var fn = function (count) {totalCount += count;}//每次调用fnfn(100);fn(200);fn(300);console.log(totalCount);//利用柯里化可以实现,把每次执行函数的结果存储起来,当你最后想得到结果的时候在停止存储。var fn2 = (function () {//把每次调用内部函数的结果都存在这个数组中,因为是闭包,这个数组不会被销毁,存在内存中。var args = [];return function () {//当没有参数传入的时候,停止,得到最后的结果if (!arguments.length) {//!arguments.length 和 arguments.length == 0 是一个意思var returnNum = 0;//遍历args取出每个结果,叠加起来,返回。for (var i = 0; i < args.length; i++) {returnNum += args[i];}return returnNum;}//把每次传进来的数值存储到args数组中// args.push(arguments[0]);[].push.apply(args, arguments);}})();fn2(100);fn2(300);fn2(600);//当函数没有传入任何参数的时候停止。得到最后的结果。console.log(fn2());</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>setInterval的使用</title></head><body><script type="text/javascript">//setInterval的使用setInterval(function () {console.log("a");}, 2000);//带参数setInterval(function (a, b) {console.log(a + b);}, 2000, 5, 5);//利用setTimeout()实现setInterval()的功能var mySetInterval = function (fn, wait) {var tempSetInterval = function () {//fn指向全局fn.call();setTimeout(tempSetInterval, wait);}//第一次的时候调用setTimeout(tempSetInterval, wait);}mySetInterval(function () {console.log("自己实现的setInterval");}, 1000);//setTimeout()函数和setInterval()函数的返回值,是一个整数类型连续的值(在正常的环境下)。//换句话说,第二个开启的setTimeout函数的返回值,要比第一个开启的值大。(function () {//0表示没有间隔,gid是返回值。用于销毁定时器var gid = setInterval(clearAllTimer, 0);//清空所有定时器function clearAllTimer () {var id = setTimeout(function () {}, 0);while (id > 0) {//除了外面轮训的gid以外 全部清空// if (id !== gid) {clearTimeout(id);// }id--;}}})();</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>飞翔的小球和弹弹球</title></head><body><div id="left_div" style="width:500px;height:500px;position:absolute;background:red;"><div id="left_fly_div" style="width:50px;height:50px;border-radius:25px;background:green;position:absolute;"></div></div><div id="right_div" style="width:500px;height:500px;position:relative;float:right;background:blue;"><div id="right_fly_div" style="width:50px;height:50px;border-radius:25px;background:red;position:absolute;" ></div></div><script type="text/javascript">//飞翔的小球//获得左边的小球divvar leftFlyDiv = document.getElementById("left_fly_div");//飞翔差值初始化var frameX = 0;var frameY = 0;//开启定时器var leftTimerId = setInterval(function () {//改变差值frameX += 1;frameY += 1;//改变小球的leftleftFlyDiv.style.left = frameX + 'px';//改变小球的topleftFlyDiv.style.top = frameY + 'px';}, 10);//弹弹球//获得右边小球的divvar rightFlyDiv = document.getElementById("right_fly_div");//获得右边外部的divvar rightDiv = document.getElementById("right_div");//初始化右边小球的left和toprightFlyDiv.style.left = "0px";rightFlyDiv.style.top = "0px";//弹弹球的差值var rightFrameX = 5;var rightFrameY = 2;// alert(rightFlyDiv.style.left);// alert(rightFlyDiv.style.width);// alert(parseInt("0px"));//开启轮询定时器var rightTimer = setInterval(function () {//先计算每次飞多少left 和 toprightFlyDiv.style.left = parseInt(rightFlyDiv.style.left) + rightFrameX + 'px';rightFlyDiv.style.top = parseInt(rightFlyDiv.style.top) + rightFrameY + 'px';//判断什么时候反向弹//左右if (parseInt(rightFlyDiv.style.left) + parseInt(rightFlyDiv.style.width) >= parseInt(rightDiv.style.width) || parseInt(rightFlyDiv.style.left) <= 0) {//改变差值rightFrameX *= -1;}//上下if (parseInt(rightFlyDiv.style.top) + parseInt(rightFlyDiv.style.height) >= parseInt(rightDiv.style.height) || parseInt(rightFlyDiv.style.top) <= 0) {//改变差值rightFrameY *= -1;}}, 10);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>飞翔的小球和弹弹球</title></head><body><div id="left_div" style="width:500px;height:500px;position:absolute;background:red;"><div id="left_fly_div" style="width:50px;height:50px;border-radius:25px;background:green;position:absolute;"></div></div><div style="float:left; width:100px;height:100px;margin-left:600px;" ><input type="button" value="开始" id="my_btn" style="width:100px;height:100px;font-size:28px;"/></div><div id="right_div" style="width:500px;height:500px;position:relative;float:right;background:blue;"><div id="right_fly_div" style="width:50px;height:50px;border-radius:25px;background:red;position:absolute;" ></div></div><script type="text/javascript">//飞翔的小球//获得左边的小球divvar leftFlyDiv = document.getElementById("left_fly_div");//飞翔差值初始化var frameX = 0;var frameY = 0;//开启定时器var leftTimerId = setInterval(function () {//改变差值frameX += 1;frameY += 1;//改变小球的leftleftFlyDiv.style.left = frameX + 'px';//改变小球的topleftFlyDiv.style.top = frameY + 'px';}, 10);var myFn = (function () {//定时器返回的timerIdvar rightTimer;//弹弹球//获得右边外部的divvar rightDiv = document.getElementById("right_div");//获得右边小球的divvar rightFlyDiv = document.getElementById("right_fly_div");//初始化右边小球的left和toprightFlyDiv.style.left = "0px";rightFlyDiv.style.top = "0px";//弹弹球的差值var rightFrameX = 5;var rightFrameY = 2;return function (flag) {//如果点击停止就清除定时器if (!flag) {clearInterval(rightTimer);return;}// alert(rightFlyDiv.style.left);// alert(rightFlyDiv.style.width);// alert(parseInt("0px"));//开启轮询定时器rightTimer = setInterval(function () {//先计算每次飞多少left 和 toprightFlyDiv.style.left = parseInt(rightFlyDiv.style.left) + rightFrameX + 'px';rightFlyDiv.style.top = parseInt(rightFlyDiv.style.top) + rightFrameY + 'px';//判断什么时候反向弹//左右if (parseInt(rightFlyDiv.style.left) + parseInt(rightFlyDiv.style.width) >= parseInt(rightDiv.style.width) || parseInt(rightFlyDiv.style.left) <= 0) {//改变差值rightFrameX *= -1;}//上下if (parseInt(rightFlyDiv.style.top) + parseInt(rightFlyDiv.style.height) >= parseInt(rightDiv.style.height) || parseInt(rightFlyDiv.style.top) <= 0) {//改变差值rightFrameY *= -1;}}, 10);}})();//按钮点击事件var myBtn = document.getElementById("my_btn");myBtn.onclick = function () {if (this.value == '开始') {this.value = '停止';myFn(true);} else {this.value = '开始';myFn(false);}}</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>div透明度渐变</title></head><body><div id="my_div" style="width:500px;height:500px;background:red;float:left;"></div><div id="right_div" style="width:500px;height:500px;background:blue;float:right;"></div><script type="text/javascript">//实现渐隐功能//获取要渐隐的divvar myDiv = document.getElementById("my_div");//透明度初始值var opacity = 1;var timerId = setInterval(function () {//每次轮训都把透明度的变量减少0.05opacity -= 0.1;if (opacity > 0) {//改变myDiv的透明度myDiv.style.opacity = opacity;} else {//手动变成0// myDiv.style.opacity = 0;//透明度没了之后,清空定时器clearInterval(timerId);}}, 100);//获取右边divvar rightDiv = document.getElementById("right_div");//手动初始化一下透明度样式,不初始化,不能直接调用rightDiv.style.opacity = 1;//渐变差值var rightOpacity = 0.1;var rightTimerId = setInterval(function () {//透明度每次改变rightDiv.style.opacity -= rightOpacity;if (rightDiv.style.opacity >= 1) {rightOpacity *= -1;} else if (rightDiv.style.opacity <= 0) {rightOpacity *= -1;}}, 100);</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>JS调用CSS遇到的问题</title><style type="text/css">#your_div {width: 200px;height: 200px;background: blue;}</style></head>asdgghffj,l.kgv<body><div id="my_div" style="width:200px;height:200px;background:red"></div><div id="your_div"></div><script type="text/javascript">//测试//获得两个divvar myDiv = document.getElementById("my_div");var yourDiv = document.getElementById("your_div");//通过style属性获得它们相应的样式console.log("myDiv = " + myDiv.style.width);console.log("yourDiv = " +yourDiv.style.width);//给yourDiv设值样式值yourDiv.style.width = "200px";console.log("yourDiv = " + yourDiv.style.width);//通过getComputedStyle()函数来获取yourDiv的高度,//不需要提前赋值就可以获取到console.log("yourDiv = " + getComputedStyle(yourDiv, null).height);//调用封装后的获取样式值console.log("yourDiv = " + getStyle(yourDiv, "height"));//封装一个通过样式属性名获取值得函数function getStyle (element, attr) {if (window.getComputedStyle) {return getComputedStyle(element, null)[attr];} else if (window.currentStyle) {return element.currentStyle[attr];} else {return element.style[attr];}}</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>鼠标点击出现DIV</title><style type="text/css">#out_div {width: 500px;height: 500px;background: red;position: relative;}#in_div {width: 100px;height: 100px;position: absolute;background: yellow;}</style></head><body><div id="out_div"><div id="in_div"></div></div><script type="text/javascript">//获得最后div要移动坐标的函数function getPosition (event) {var x = event.clientX; //获得鼠标当前在浏览器中的x坐标var y = event.clientY; //获得鼠标当前在浏览器中的y坐标var r = event.target.getBoundingClientRect(); //获取在浏览器中被点击元素的范围信息//鼠标最后点击的x、y的位置x -= r.left;y -= r.top;//把最后的x、y 封装到一个对象中 返回。var positionObj = {m_x : x,m_y : y}return positionObj;}//给out_div添加单击事件var outDiv = document.getElementById("out_div");outDiv.onclick = function (event) {//获得in_divvar inDiv = document.getElementById("in_div");//判断是否点击在了inDiv上if (event.target === inDiv) {return;}//否则改变inDiv的位置var positionObj = getPosition(event);inDiv.style.left = positionObj.m_x + "px";inDiv.style.top = positionObj.m_y + "px";}</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>ipone秒表</title><style type="text/css">#out_div{width: 350px;height: 500px;margin: 0 auto;background: #ccc;}#top_div {width: 350px;height: 200px;background: red;}#center_div{width: 350px;height: 100px;background: green;}#bottom_div {width: 350px;height: 200px;background: orange;}h3{text-align: center;line-height: 40px;}#small_span {display: block;height: 50px;text-align: right;font-size: 35px;margin-right: 20px;}#big_span {display: block;height: 50px;text-align: right;font-size: 60px;margin-right: 20px;}#left_btn {width: 50px;height: 50px;margin-top: 15px;margin-left: 125px;font-size: 20px;}#right_btn {width: 50px;height: 50px;margin-top: 15px;font-size: 20px;}</style></head><body><div id="out_div"><div id="top_div"><h3>秒表</h3><hr /><span id="small_span">00:00.00</span><span id="big_span">00:00.00</span></div><div id="center_div"><input type="button" value="计次" id="left_btn" disabled /><input type="button" value="启动" id="right_btn"/></div><div id="bottom_div"></div></div><script type="text/javascript">//秒表的实现var timerfn = (function () {//定时器的返回值var timerId;//获取两个时间文本var smallSpan = $("small_span");var bigSpan = $("big_span");var smallM = 0; //分var smallS = 0; //秒var smallMS = 0; //毫秒var smallMMSS = 0; //微秒var bigM = 0; //分 (大)var bigS = 0; //秒var bigMS = 0; //毫秒var bigMMSS = 0; //微秒return function (flag, type) {if (!flag) {if (type == '复位') {//清空small的文本为0smallMMSS = 0;smallMS = 0;smallS = 0;smallM = 0;//清空big的文本为0bigMMSS = 0;bigMS = 0;bigS = 0;bigM = 0;//文本也清空smallSpan.innerHTML = "00:00.00";bigSpan.innerHTML = "00:00.00";}clearInterval(timerId);return;}//如果当前type是计次if (type == '计次') {//清空small的文本为0smallMMSS = 0;smallMS = 0;smallS = 0;smallM = 0;//初不初始化都行。// smallSpan.innerHTML = "00:00.00";}timerId = setInterval(function () {//小的时间递增smallMMSS++;if (smallMMSS == 10) {smallMMSS = 0;smallMS++;if (smallMS == 10) {smallMS = 0;smallS++;if (smallS == 60) {smallS = 0;smallM++;//..}}}//大的时间递增bigMMSS++;if (bigMMSS == 10) {bigMMSS = 0;bigMS++;if (bigMS == 10) {bigMS = 0;bigS++;if (bigS == 60) {bigS = 0;bigM++;//..}}}//赋值smallSpan.innerHTML = smallM + ":" + smallS + "." + smallMS + smallMMSS;bigSpan.innerHTML = bigM + ":" + bigS + "." + bigMS + bigMMSS;}, 10);}})();//右边按钮的事件$("right_btn").onclick = function () {if (this.value == '启动') {this.value = '停止';//左边按钮变计次$("left_btn").value = '计次';//左边按钮解禁$("left_btn").disabled = null;timerfn(true);} else {this.value = '启动';//左边按钮变成复位$("left_btn").value = '复位';timerfn(false);}}//左边按钮事件$("left_btn").onclick = function () {if (this.value == '计次') {//先清空,在启动timerfn(false, this.value);timerfn(true, this.value);} else {//清掉所有数据,并且暂停timerfn(false, this.value);this.value = '计次';//还要变成禁用的this.disabled = "disabled";}}//封装通过ID获得元素的函数function $ (idName) {return document.getElementById(idName);}</script></body></html>
4.3 映射与集合Map 类型,也称为简单映射,只有一个目的:保存一组键值对儿。开发人员通常都使用普通对象来保存键值对儿, 但问题是那样做会导致键容易与原生属性混淆。 简单映射能做到键和值与对象属性分离,从而保证对象属性的安全存储。以下是使用简单映射的几个例子。var map = new Map();map.set("name", "Nicholas");map.set("book", "Professional JavaScript");console.log(map.has("name")); //trueconsole.log(map.get("name")); //"Nicholas"map.delete("name");简单映射的基本 API 包括 get() 、 set() 和 delete() ,每个方法的作用看名字就知道了。键可以是原始值,也可是引用值。与简单映射相关的是 Set 类型。 集合就是一组不重复的元素。 与简单映射不同的是, 集合中只有键,没有与键关联的值。在集合中,添加元素要使用 add() 方法,检查元素是否存在要使用 has() 方法,而删除元素要使用 delete() 方法。以下是基本的使用示例。var set = new Set();set.add("name");console.log(set.has("name")); //trueset.delete("name");console.log(set.has("name")); //false
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>Map的简单使用</title></head><body><script type="text/javascript">//创建一个map对象var map = new Map();//给map添加键值对map.set("a", "刘升升");map.set("b", "王沫沫");map.set("d", {name : "张晓晓", age : 18});map.set("c", 18);//添加一个重复的键map.set("a", "李屌屌");//通过键获得值console.log(map.get("a"));console.log(map);//forEach遍历Mapmap.forEach(function (value, key, map) {//三个参数分别代表//value:map当前键对应的值。//key:map当前的键//map:就是map本身的对象console.log("键:" + key);console.log("值:" + value);if (key == 'd') {console.log(value.age);}});var arr = ["a", "b", "c"];//数组遍历arr.forEach(function (element, idx, array) {//element:数组的当前元素//idx:下标//array:当前array对象console.log(array);});</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>公司部门员工的业务编程</title></head><body><script type="text/javascript">/*3、业务编程题。需求:员工类(Staff)属性:员工姓名(name)所在部门名字(departmentName)(是一个字符串)入职时间(time)(例如:2015 这种格式的字符串即可)公司类(Company)属性:部门:(departmentMap) (类型是一个Map,Map的键是部门的名字,值是对应部门的员工数组,员工数组里是每个员工对象)方法:1、添加员工要求:首先员工姓名和入职时间不能同时重复。 如果添加的员工所在部门不存在,你需要帮他创建该部门,如果存在直接加入该部门即可。2、交换员工的部门(参数是:部门员工和要交换的部门名字)*///员工构造函数var Staff = function (name, time, departmentName) {this.name = name;this.time = time;this.departmentName = departmentName;}//公司构造函数var Company = function () {this.departmentMap = new Map();}//添加员工的方法// 要求:首先员工姓名和入职时间不能同时重复。 如果添加的员工所在部门不存在,你需要帮他// 创建该部门,如果存在直接加入该部门即可。Company.prototype.addStaff = function (newStaff) {//声明一个return标识var flag = true;//遍历部门的mapthis.departmentMap.forEach(function (value, key, map) {//遍历每个员工数组,因为value就已经是map遍历出来的值,值就是员工数组。value.forEach(function (element, idx, array) {//判断每个员工对象是否和新员工对象的名字和入职时间相同。if (element.name == newStaff.name && element.time == newStaff.time) {console.log("不能重复添加新员工!");//当员工重复的时候,flag=falseflag = false;// return;}});});//当flag为true的时候,说明新加的员工名字和时间不重复,则可以新加员工。if (flag) {//获得新添加员工所在部门,判断其部门是否存在(以后这块儿用map的has方法判断)var staffArray = this.departmentMap.get(newStaff.departmentName);if (typeof staffArray == 'undefined') {//新创建的员工数组staffArray = new Array();//新添加的员工staffArray.push(newStaff);//新创建的部门this.departmentMap.set(newStaff.departmentName, staffArray);} else {//如果部门存在直接添新员工即可staffArray.push(newStaff);}}}//查看所有员工的方法(格式化输出)Company.prototype.showAllStaffs = function () {//遍历部门mapthis.departmentMap.forEach(function (value, key, map) {//打印部门console.log(key + ":");//遍历员工数组value.forEach(function (element, idx, array) {console.log(" 姓名:" + element.name + "\n 时间:" + element.time);});});}//交换员工所在部门(参数:要交换的员工对象,要交换的部门名字)Company.prototype.changeStaffDepartment = function (changeStaff, changeDepartmentName) {//1、把该员工之前所在部门剔出去。// this.departmentMap.delete("品质保障部");//遍历部门mapthis.departmentMap.forEach(function (value, key, map) {//遍历员工数组value.forEach(function (element, idx, array) {//找出要交换的员工if (element === changeStaff) {//删除该员工value.splice(idx, 1);//改变下标// idx--; 注意:因为新加员工的时候,已经判断不能重复添加,所以这里只能找到唯一的一个员工对象进行删除。return;}});});//添加到新部门//判断新加部门存不存在,不存在就创建该部门,把这个人加进去。var staffArray = this.departmentMap.get(changeDepartmentName);if (typeof staffArray == 'undefined') {staffArray = new Array();staffArray.push(changeStaff);this.departmentMap.set(changeDepartmentName, staffArray);} else {staffArray.push(changeStaff);}}//创建公司对象var c = new Company();//创建很多员工对象var s1 = new Staff("小芳", "2015", "品质保障部");var s2 = new Staff("小薇", "2016", "品质保障部");var s3 = new Staff("小芳", "2015", "独立部");var s4 = new Staff("小芳", "2016", "程序猿鼓励部");var s5 = new Staff("小黑", "2013", "单身部");//添加新员工c.addStaff(s1);c.addStaff(s2);c.addStaff(s3);c.addStaff(s4);c.addStaff(s5);//显示所有员工及部门c.showAllStaffs();//打印分隔符console.log("\n ================");//交换员工部门c.changeStaffDepartment(s2, "程序猿鼓励部");c.changeStaffDepartment(s4, "UI设计部");//显示所有员工c.showAllStaffs();</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>字符串题</title></head><body><script type="text/javascript">/*(易)传入:"iOS Android HTML5 Java"返回:"avaJ 5LMTH diordnA SOi"函数名:function reverseString (str) ;//字符串也可以进行遍历,可以得到每个字符*/function reversString (str) {//最终返回结果var resultStr = "";//逆序遍历for (var i = str.length - 1; i >= 0; i--) {//得到每个字符var tempChar = str[i];resultStr += tempChar;}return resultStr;}console.log(reversString("iOS Android HTML5 Java"));/*(难)传入:"iOS Android HTML5 Java"返回:"SOi diordnA 5LMTH avaJ"函数名: function reverseStringByWords (str) ;*/function reverseStringByWords (str) {//返回结果var resultStr = "";//切割字符串var arr = str.split(" ");//遍历数组for (var i = 0; i < arr.length; i++) {//得到每个元素(其实就是每个单词字符串)var tempStr = arr[i];//逆序遍历每个tempStrfor (var j = tempStr.length - 1; j >= 0; j--) {//获得每个字符var tempChar = tempStr[j];//拼接起来resultStr += tempChar;}resultStr += " ";}//这么做的话最后一步记得截取空格。会返回一个新的字符串return resultStr.substr(0, resultStr.length - 1);}console.log(reverseStringByWords("iOS Android HTML5 Java"));</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>按钮改变背景颜色</title></head><body><input type="button" id="btn_1" name="btn" value="开始" /><span id="span_1">0</span><br /><input type="button" id="btn_2" name="btn" value="开始" /><span id="span_2">0</span><br /><input type="button" id="btn_3" name="btn" value="开始" /><span id="span_3">0</span><script type="text/javascript">/*页面有3个按钮(每个按钮默认的value是“开始”)对应3个span(span内的innerHTML默认是0)。要求:每点击一个按钮(value的值开始变停止),开启一个轮询定时器进行对应span标签内的数字从0-255随机滚动,在点击一下(value的值停止变开始,定时器也跟着停止。)要求得到3个的span内innerHTML的值,并且通过这三个值把body的背景颜色改变一下。(也就是说每次点击某个按钮后,先判断其他两个是否停下来,全部都停下来后才可以去改变背景颜色)*///获取所有button元素var buttons = document.getElementsByName("btn");//给每个button添加单击事件for (var i = 0; i < buttons.length; i++) {buttons[i].onclick = function () {//定时器的timerIdvar timerId;if (this.value == '开始') {this.value = '停止';console.log(this.id);//需要保存当前this指针,供内部函数使用var that = this;//如果是多个按钮触发同一个事件的话,定时器不要写在外面。写在外面会共享同一个定时器,会有各种问题。timerId = setInterval(function () {//在轮训的时候点击按钮停止if (that.value == '开始') {clearInterval(timerId);if ($("btn_1").value == '开始' && $("btn_2").value == '开始' && $("btn_3").value == '开始') {//改变背景颜色document.body.style.backgroundColor = "rgb(" + $('span_1').innerHTML + "," + $('span_2').innerHTML + "," + $('span_3').innerHTML + ")";};}//得到点击按钮id的编号// console.log(that.id);var idx = that.id.split("_")[1];//获得对应的span元素,并且赋值$("span_" + idx).innerHTML = Math.floor(Math.random() * 256);}, 100);// fn(true);} else {this.value = '开始';// clearInterval(timerId);}}}//封装通过ID获取元素的方法function $ (idName) {return document.getElementById(idName);}// var fn = (function () {// var timerId;// return function () {// timerId....定时器// }// })();</script></body></html>
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>作业3</title></head><body><script type="text/javascript">/** 3、综合题(难)按步骤做:1)通过ajax解析本地服务器的kaoshi.json文件,在解析的过程中封装数据模型(也就是提前准备好相应的构造函数,json文件中有什么,就弄多少构造函数。最后解析的方法,会返回一个班级的对象,也就是说,有这个班级对象,就能有所有的数据)函数名:function analysisJSON(){};2)给班级构造函数定义:- 显示所有学生信息的方法(先按照学生名字长度进行有大到小排序,如果长度相等,在按照字符串大小进行有大到小排序)方法名:showAllStudentsSortByName();3)给班级构造函数定义:- 改变每个学生性别的方法(男变女,女变男),然后在该方法内部调用显示所有学生信息的方法方法名:changeAllStudentsSex();**///1、ajax异步请求json文件var xhr;if (window.XMLHttpRequest) {xhr = new XMLHttpRequest();} else if (window.ActiveXObject) {var versions = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];for (var i = 0; i < versions.length; i++) {try {xhr = new ActiveXObject(versions[i]);break;} catch (e) {alert(e);}}} else {throw new Error("浏览器不支持Ajax");}//打开链接xhr.open("GET", "kaoshi.json", true);//发送请求xhr.send(null);//接收服务器响应xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {//转换成json字面量对象var jsonObj = JSON.parse(xhr.responseText);console.log(jsonObj);//获得班级的字面量对象var classObj = jsonObj.class;// 创建班级数据模型的对象var classModel = new ClassModel(classObj.className);//获得老师字面量对象var teacherObj = classObj.teacher;//创建老师数据模型的对象var teacherModel = new TeacherModel(teacherObj.sex, teacherObj.teacherName);//把老师的数据模型对象赋值给 班级数据模型对象的老师属性classModel.teacher = teacherModel;//获得字面量学生数组var studentArray = classObj.studentArray;//遍历字面量学生数组for (var tempStudentIdx in studentArray) {//得到每一个学生字面量对象var studentObj = studentArray[tempStudentIdx];//创建学生数据模型对象var studentModel = new StudentModel(studentObj.sex, studentObj.studentName, studentObj.studentCode);//添加学生数据模型到班级的学生数组中classModel.studentArray.push(studentModel);}// console.log(classModel);//显示所有学生信息classModel.showAllStudentsSortByName();console.log("\n ==================== ");//改变学生性别classModel.changeAllStudentsSex();}}//班级模型构造函数function ClassModel (className, teacher) {this.className = className;this.studentArray = new Array();this.teacher = teacher;}//显示所有学生信息的方法ClassModel.prototype.showAllStudentsSortByName = function () {//冒泡排序for (var i = 0; i < this.studentArray.length - 1; i++) {for (var j = 0; j < this.studentArray.length - i - 1; j++) {//获得要交换位置的两个元素var tempStudent1 = this.studentArray[j];var tempStudent2 = this.studentArray[j + 1];//判断名字的长度if (tempStudent1.studentName.length < tempStudent2.studentName.length) {//交换位置this.studentArray.splice(j, 1, tempStudent2);this.studentArray.splice(j + 1, 1, tempStudent1);} else if (tempStudent1.studentName.length == tempStudent2.studentName.length) {//如果长度相同,在比较大小if (tempStudent1.studentName <= tempStudent2.studentName) {//交换位置this.studentArray.splice(j, 1, tempStudent2);this.studentArray.splice(j + 1, 1, tempStudent1);}}}}//显示学生信息//遍历学生数组this.studentArray.forEach(function (element) {console.log("姓名:" + element.studentName + " 性别:" + element.sex + " 学号:" + element.studentCode);});}//改变学生性别的方法ClassModel.prototype.changeAllStudentsSex = function () {//遍历所有学生this.studentArray.forEach(function (element) {if (element.sex == '男') {element.sex = '女';} else {element.sex = '男';}});//调用显示学生信息的方法this.showAllStudentsSortByName();}//老师模型构造函数function TeacherModel (sex, teacherName) {this.sex = sex;this.teacherName = teacherName;}//学生的构造函数function StudentModel (sex, studentName, studentCode) {this.sex = sex;this.studentName = studentName;this.studentCode = studentCode;}</script></body></html>
{"class" : {"className" : "HTML51604","studentArray" : [{"sex" : "男","studentCode" : "160401","studentName" : "丁环宇"},{"sex" : "男","studentCode" : "160402","studentName" : "武戈"},{"sex" : "男","studentCode" : "160403","studentName" : "严帅"},{"sex" : "女","studentCode" : "160404","studentName" : "马丹丹"},{"sex" : "女","studentCode" : "160405","studentName" : "卢欢"},{"sex" : "男","studentCode" : "160406","studentName" : "段俊岩"},{"sex" : "男","studentCode" : "160407","studentName" : "吴贤青"},{"sex" : "女","studentCode" : "160408","studentName" : "马钰琦"},{"sex" : "男","studentCode" : "160409","studentName" : "崔晋龙"},{"sex" : "男","studentCode" : "160410","studentName" : "彭铖"},{"sex" : "女","studentCode" : "160411","studentName" : "王鹏"}],"teacher" : {"sex" : "男","teacherName" : "刘升旭"}}}
【jQuery选择器】1、重新认识下DOMjQuery的强大之处,就在于它能够简化DOM的操作。DOM(Document Object Model)文档对象模型,它就是javascript与HTML间的接口。DOM的结构就像我们生活中家族谱一样,所以我们会像家族谱那样形容DOM的结构,比如:父元素、子元素、兄弟元素等。2、基本选择器jQuery构造函数,通过传入CSS选择器作为参数,能让我们轻松的获得想要的元素或元素集合。- ID选择器:$("#my_div") 获得id为my_div的元素- 元素选择器:$("p") 获得所有p元素- 类选择器:$(".my_class") 获得类名为my_class的所有元素- 属性选择器:$("[name = my_name]") 获得元素name属性为 my_name的所有元素- 组合选择器:$("div.my_class") 获得类名为my_class的所有div元素【多项选择器】可以获得多个元素。$('div,p') 获得所有的div 和 p 元素【层级选择器】因为DOM的结构是有层级的,所以有的时候基本选择器满足不了我们,我们会经常使用层级选择器。如果两个DOM元素具有层级关系,就可以使用层级选择器。层级说的就是祖先和后代的意思。层级之间用空格隔开$('ul.my_class li') 获取类名为my_class的ul元素下的 所有 li元素---看层级选择器.html【子选择器】子选择器类似于层级选择器。$('parentNode>childNode')不同于层级选择器的地方是,限定了层级关系一定是父子的关系才行。也就是说childNode是parentNode的直接子节点。---看层级选择器.html【过滤选择器】过滤选择器一般不单独使用,通常附加在其他选择器上使用。能够更精确找到我们想要的元素。---看层级选择器.html【表单选择器】针对表单,jQuery提供了一套关于查找表单的选择器---看表单选择器.html【查找和过滤】有的时候我们通过各种选择器获得相应的元素后,我们要对这些结果集在进一步进行过滤或者查找。---看查找和过滤.html
【jQueryDOM节点相关】注意:以下说的都是方法。1、父子节点相关append:将参数中的元素插入当前元素的尾部appendTo:将当前元素插入参数元素中的尾部prepend:将参数中的元素变为当前元素的第一个子元素prependTo:将当前元素变为参数元素的第一个子元素2、兄弟节点相关after:将参数中的元素插入到当前元素的后面insertAfter:将当前元素插入到参数元素的后面before:将参数中的元素插入到当前元素的前面insertBefore:将当前元素插入到参数元素的前面3、移除相关remove:移除元素replaceWith:将当前元素替换成参数中的元素
【jQuery动画】注意:以下说的都是方法1、一些动画效果的简单写法show:显示当前元素hide:隐藏当前元素toggle:隐藏或显示当前元素fadeOut:渐变(透明度)消失当前元素fadeToggle:渐变或渐隐slideDown:从上向下出现当前元素(滑动)slideUp:从下向上隐藏当前元素(滑动)slideToggle:切换上面的效果2、animate方法以上那些简单的写法,实际上内部都调用了这个animate方法。animate方法可以接受3个参数:- 第一个参数设置CSS属性- 第二个参数动画时长- 第三个参数回调函数3、stop方法、delay方法stop:表示立即停止动画delay:接受一个参数,表示暂停多少毫秒之后继续执行【each方法遍历】语法:$(selector).each(function (idx, element) {});idx:每个选择器的下标element:当前元素(也可以用$(this)表示)
【jQuery的事件】jQuery的事件和大部分JS事件用法相同。例如:$(selector).click(function () {});这里就不一一举例了。但要说一下hover事件。hover:这个方法接受2个参数,分别代表移入和移除。也可以是一个参数,表示移入或移除触发同一个函数。【on方法】on方法是jQuery事件的统一接口。其他事件绑定的方法其实都是on方法的实现。on方法可以接受2个参数,一个表示事件类型,一个表示回调函数。on方法也可以一次性添加2个事件,这2个事件,会触发同一个回调函数。【off方法】off方法移除事件的回调函数【事件的命名空间】同一个元素有的时候可以绑定多个事件,如果想移除其中一个,可以采用“命名空间”的方式。即为每个事件定义一个二级的名称,然后利用off方法可以移除这个二级事件名称。【event对象】当回调函数触发后,可以接受一个参数,这个参数就是event对象evnet的属性:- type:事件的类型- target:事件源- data:传入事件对象的数据- pageX:事件发生时,鼠标水平坐标- pageY:事件发生时,鼠标垂直坐标【one方法(一次性事件)】one方法绑定的事件,只会调用一次这个回调函数,一般表单提交的时候会用到这个。【解决jQuery库与其他库冲突的办法】有的时候其他库,也会使用美元符号$。难免会造成冲突。可以使用$.noConflict()方法来使jquery中$失效。今天要做的东西:1、滑动菜单2、表格过滤查找3、下拉框左右选人(ajax请求数据,jQuery版本)4、正常下拉框(ajax请求数据,jQuery版本)5、可编辑的表格(ajax请求数据,jQuery版本)6、手风琴效果(ajax请求数据,jQuery版本)
//jQuery 的 ajax通用方法$.ajax({url : "car.json", //请求路径dataType : "json", //返回数据格式async : true, //是否是异步请求,默认是异步的data : {"id" : "123"}, //参数type : "GET", //请求方式beforeSend : function () { //请求之前调用的函数console.log("==========before==============");},success : function (dd) { //成功回调函数// console.log(JSON.parse(dd));//注意:这里的格式已经帮你转换好了JS对象console.log(dd);},complete : function () { //请求完毕回调函数(无论成功失败都调用)console.log("=========complete==============");},error : function () { //失败回调函数console.log("===========error================");}});//ajax请求数据$.getJSON(' url ', null, function (data) {// data即为根数据, 已经自动反序列化为字面量对象}
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>jQuery的基本选择器</title><!-- 导入jQuery --><script src="../jquery/jquery-2.2.3.js"></script></head><body><p>第一个p标签。</p><p id="my_p">id为my_p的p标签。</p><span class="my_class" name="my_name">这是第一个span标签。</span><p class="my_class">这是一个my_class的p标签。</p><input class="your_class" type="button" name="my_name" value="按钮" /><script type="text/javascript">//获得id为my_p 的元素var p1 = $('#my_p');//JS版本// var p1 = document.getElementById('my_p');// p1.innerHTML 错!因为这是一个jQuery对象,只能调用jQuery的属性和方法。console.log(p1.html());//如果获取一个没有的id元素,不会像原生JS那样得到一个undefined或者是null的值,而是返回的[],这也避免了,去判断 一个元素是否是 undefined的操作。//jQuery对象和DOM对象的转换var p2 = $("#my_p"); //获得jQuery对象console.log(p2.html());var domP = p2.get(0); //jQuery对象转换成DOM对象console.log(domP.innerHTML);var p3 = $(domP); //DOM对象转换成jQuery对象console.log(p3.html());//元素选择器var p4 = $('p');//JS版本// var p4 = document.getElementsByTagName('p');console.log(p4.html()); //如果很多,默认是第一个。for (var i = 0; i < p4.length; i++ ) {console.log(p4[i].innerHTML);}//类选择器var class_1 = $('.my_class');//JS版本// var class_1 = document.getElementsByClassName('my_class');for (var i = 0; i < class_1.length; i++) {console.log(class_1[i].innerHTML);}//属性选择器var attr1 = $('[name = my_name]');console.log(attr1.length);//通过属性值前缀获得//获得class属性值前缀为my_的元素var attr2 = $('[class ^= my_]');console.log(attr2.length);//通过属性值后缀获得//获得class属性值后缀为_class的元素var attr3 = $('[class $= _class]');console.log(attr3.length);//组合选择器//元素和属性组合var zuHe1 = $('input[name = my_name]');//val() 和 JS的value 一样//打印这个button的valueconsole.log(zuHe1.val());</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>层级选择器</title><script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script></head><body><div class="test_div"><ul class="lang"><li class="lang_javascript">JavaScript</li><li class="lang_java">Java</li><li class="lang_php">Php</li><li class="lang_swift">Swift</li></ul></div><div><ul><li class="lang_javascript">JavaScript</li><li class="lang_java">Java</li><li class="lang_php">Php</li><li class="lang_swift">Swift</li></ul></div><div style="display:none;">这是一个div</div><script type="text/javascript">$(document).ready(function () {//多项选择器//获得所有的div和li标签var many1 = $('div,li');console.log(many1.length);//层级选择器//获得javascript所在的li标签var js_0 = $('div li.lang_javascript');console.log(js_0.length);var js_1 = $('ul li.lang_javascript');console.log(js_1.length);//获得javascript所在的li标签 ,要求li所在的ul标签的类名为langvar js_2 = $('ul.lang li.lang_javascript');console.log(js_2.html());//层级选择器相比较单个选择器的好处在于,它缩小了选择范围,因为首先先要确定祖先元素,之后再祖先元素内进行相应的查找。//子选择器var js_3 = $('ul.lang>li.lang_javascript');console.log(js_3.html());//错误案例(因为这个不是父子关系,是一种层级关系)var js_4 = $('div.test_div>li.lang_javascript');console.log(js_4.html());//过滤选择器//获得类名为lang的ul元素下所有li元素var filter_1 = $('ul.lang li');console.log(filter_1[2].innerHTML);//获得类名为lang的ul元素下所有li元素中的第一个livar filter_2 = $('ul.lang li:first');console.log(filter_2.html());//获得类名为lang的ul元素下所有li元素中的最后一个livar filter_3 = $('ul.lang li:last');console.log(filter_3.html());//获得类名为lang的ul元素下所有li元素中的某一个livar filter_4 = $('ul.lang li:eq(1)');console.log(filter_4.html());//获得类名为lang的ul元素下所有li元素中的偶数livar filter_5 = $('ul.lang li:even');console.log(filter_5[0].innerHTML + "---" + filter_5[1].innerHTML);//获得类名为lang的ul元素下所有li元素中的奇数livar filter_6 = $('ul.lang li:odd');console.log(filter_6[0].innerHTML + "===" + filter_6[1].innerHTML);//获得类名为lang的ul元素下所有li元素中的php之前的li元素var filter_7 = $('ul.lang li:lt(2)');console.log(filter_7[0].innerHTML + "===" + filter_7[1].innerHTML);//获得类名为lang的ul元素下所有li元素中的php之后的li元素var filter_8 = $('ul.lang li:gt(2)');console.log(filter_8.html());//获得隐藏的div标签var filter_9 = $('div:hidden');console.log(filter_9.html());//获得显示的div标签var filter_10 = $('div:visible');console.log(filter_10.length);});// $(function () {// });</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>表单选择器</title><script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script></head><body><form action="#" method="get">姓名:<input type="text" value="周xixi" disabled/><br />密码:<input type="password" /><br />性别:<input type="radio" name="r"/> 男 <input type="radio" name="r" /> 女<br />兴趣:<input type="checkbox" name="x" /> 跑步<input type="checkbox" name="x" /> 健身<input type="checkbox" name="x" /> 打LOL<br />国籍:<select multiple><option>中国</option><option>美国</option><option>日本</option><option>俄罗斯</option></select><br /><input type="button" value="注册" onclick="btn_click();" /></form><script type="text/javascript">function btn_click () {//表单选择器//获得所有input元素var form_1 = $(":input");console.log(form_1.length);//获得type为text的元素var form_2 = $(':text');console.log(form_2.val());//获得所有被选中的元素var form_3 = $(':checked');console.log(form_3.length);//获得所有checkbox被选中的元素var form_4 = $('[type=checkbox]:checked');var form_5 = $(':checkbox:checked');console.log(form_5.length);//获得被selected选中的元素var form_6 = $(':selected');console.log(form_6.val());console.log(form_6.length);//获得禁用的表单元素var form_7 = $(':disabled');console.log(form_7.val());}</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>查找和过滤</title><script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script></head><body><div class="test_div"><ul class="lang"><li class="js">javascript</li><li class="py">python</li><li class="java">java</li><li id="swift">swift</li><li name="php">php</li></ul></div><script type="text/javascript">$(document).ready(function () {/*first()、 last()、eq()方法(都会参照上一步的结果集)*///第一个var f_1 = $('ul.lang li').first();console.log(f_1.html());//最后一个var f_2 = $('ul.lang li').last();console.log(f_2.html());//某一个var f_3 = $('ul.lang li').eq(3);console.log(f_3.html());/*next()、prev()方法下一个、上一个*/var f_4 = $('ul.lang li').eq(3).next();console.log(f_4.html());var f_5 = $('ul.lang li').last().prev().prev();console.log(f_5.html());/*parent()、parents()、children();parent():某元素的父元素parents():某元素的祖先元素们(直到html)children():某元素的孩子元素们*/var f_6 = $('ul.lang li').first().parent();console.log(f_6.html());var f_7 = $('ul.lang li').first().parents();console.log(f_7.length);//parents() 可以设置参数,进行限制var f_8 = $('ul.lang li').first().parents('div');console.log(f_8.html());//children()方法是获得某个节点下的所有孩子节点var f_9 = $('ul.lang').children();console.log(f_9.length);//获得ul下的name为php的孩子们var f_10 = $('ul.lang').children('[name=php]');console.log(f_10.html());/*siblings()、nextAll()、preAll() 都是同一级操作siblings():获得当前元素的所有兄弟元素nextAll():获得当前元素的所有后面的兄弟元素prevAll():获得当前元素的所有前面的兄弟元素*/var f_11 = $('ul.lang li').first().siblings().eq(2);console.log(f_11.html());var f_12 = $('ul.lang li').first().siblings(':eq(2)');console.log(f_12.html());var f_13 = $('ul.lang li').eq(2).nextAll(':eq(1)');// console.log(f_13.length);console.log(f_13.html());var f_14 = $('ul.lang li').last().prevAll(':eq(0)');console.log(f_14.html());/*find()查找某个元素的所有子元素(按照条件)filter()得到某些结果集后进行条件过滤not()得到某些结果集后,利用not()方进行进行排除*/var f_15 = $('ul.lang').find('.java');console.log(f_15.html());var f_16 = $('ul.lang li').filter('.java');console.log(f_16.html());var f_17 = $('ul.lang li').not('[name=php]').last();// console.log(f_17.length);console.log(f_17.html());});</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>DOM的一些简单方法使用</title><script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script><style type="text/css">.my_class {font-size: 30px;}</style></head><body><div><ul id="lang"><li class="js">javascript</li><li name="js_lang">javascript & java</li></ul></div><p id="my_p">这是一个段落。</p><div id="my_div"></div><input type="button" value="html/text" onclick="htFn(this);" /><br /><input type="button" value="addClass" onclick="addClassFn(this);" /><br /><input type="button" value="removeClass" onclick="removeClassFn(this);" /><br /><input type="button" value="toggleClass" onclick="toggleClassFn(this);" /><br /><input type="button" value="css" onclick="cssFn(this);" /><br /><input type="button" value="val" onclick="valFn(this);" /><br /><input type="button" value="attr" onclick="attrFn(this);" /><br /><input type="button" value="removeAttr" onclick="removeAttrFn(this);" /><script type="text/javascript">//html() 和 text()//获取和设置function htFn (ele) {//获取var ht = $('#lang li[name=js_lang]').html();var txt = $('#lang li[name=js_lang]').text();console.log(ht);console.log(txt);//设值$('#my_div').html('<span style="color:red;">这其实是一个span。</span>');$('#my_div span').text("JS & Java");}//添加类classfunction addClassFn (ele) {$('#my_p').addClass('my_class');}//移除类classfunction removeClassFn (ele) {$('#my_p').removeClass('my_class');}//自动切换添加和移除类的方法function toggleClassFn (ele) {$('#my_p').toggleClass('my_class');}//css() 可以获取和设置 元素的css样式function cssFn (ele) {//获取某个样式属性值var cssValue = $('#my_p').css('font-size');console.log(cssValue);//设置某个样式属性值$('#my_p').css('font-size', '50px');//设置多个可以这么写$('#my_p').css({'font-size' : '30px','color' : 'red'});}//val() 可以获取值 和 设置值function valFn (ele) {//获取//注意:ele是JS的this指针,需要转换成jQuery对象才能使用val()方法var valValue = $(ele).val();console.log(valValue);//设值$(ele).val('改变值了');}//attr(); 获得html元素的某个属性的值,也可以设值function attrFn (ele) {//获取var attrValue = $(ele).attr('type');console.log(attrValue);//设值$(ele).attr('value', '随便');}//removeAttr() 这个方法是移除某个属性function removeAttrFn (ele) {//移除$(ele).removeAttr('value');console.log($(ele).attr('value'));}</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>DOM节点相关</title><script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script><style type="text/css">.my_class1{background: red;width: 300px;height: auto;}.my_class2{background: green;width: 300px;height: 200px;}</style></head><body><div class="my_class1"></div><div class="my_class2"><p>我是第一个p标签</p><p>我是第二个p标签</p></div><input type="button" id="append" value="append" /><br /><input type="button" id="appendTo" value="appendTo" /><br /><input type="button" id="prepend" value="prepend" /><br /><input type="button" id="prependTo" value="prependTo" /><br /><input type="button" id="after" value="after" /><br /><input type="button" id="insertAfter" value="insertAfter" /><br /><input type="button" id="before" value="before" /><br /><input type="button" id="insertBefore" value="insertBefore" /><br /><input type="button" id="remove" value="remove" /><br /><input type="button" id="replaceWith" value="replaceWith" /><br /><script type="text/javascript">$(function () {//append:将参数中的元素插入当前元素的尾部$('#append').get(0).onclick = function () {$('.my_class1').append('<p>append的段落标签</p>');}//appendTo:将当前元素插入参数元素中的尾部$('#appendTo').get(0).onclick = function () {$('<p>appendTo的段落标签</p>').appendTo($('.my_class1'));}//prepend:将参数中的元素变为当前元素的第一个子元素$('#prepend').get(0).onclick = function () {$('.my_class2').prepend($('.my_class2 p:last'));}//prependTo:将当前元素变为参数元素的第一个子元素$('#prependTo').get(0).onclick = function () {$('.my_class2 p:last').prependTo($('.my_class2'));}//after:将参数中的元素插入到当前元素的后面$('#after').get(0).onclick = function () {$('.my_class2 p:last').after($('.my_class2 p:first'));}//insertAfter:将当前元素插入到参数元素的后面$('#insertAfter').get(0).onclick = function () {$('.my_class2 p:first').insertAfter($('.my_class2 p:last'));}//before:将参数中的元素插入到当前元素的前面$("#before").get(0).onclick = function () {$('.my_class2 p:first').before($('.my_class2 p:last'));}//insertBefore:将当前元素插入到参数元素的前面$('#insertBefore').get(0).onclick = function () {$('.my_class2 p:last').insertBefore($('.my_class2 p:first'));}//remove:移除元素$('#remove').get(0).onclick = function () {$(this).remove();}//replaceWith:将当前元素替换成参数中的元素$('#replaceWith').get(0).onclick = function () {$(this).replaceWith('<p style="color:red;">被我替换了!!</p>');}});</script></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>jQuery动画</title><script type="text/javascript" src="../jquery/jquery-2.2.3.js"></script><style type="text/css">.my_class{background: red;width: 300px;height: 300px;position: absolute;left: 300px;}</style></head><body><div class='my_class'></div><input type="button" value="show" /><br /><input type="button" value="hide" /><br /><input type="button" value="toggle" /><br /><input type="button" value="fadeIn" /><br /><input type="button" value="fadeOut" /><br /><input type="button" value="fadeToggle" /><br /><input type="button" value="slideDown" /><br /><input type="button" value="slideUp" /><br /><input type="button" value="slideToggle" /><br /><input type="button" value="animate" /><br /><input type="button" value="stop" /><br /><input type="button" value="delay" /><br /><script type="text/javascript">$(function () {//show$('input[value=show]').click(function () {// $('.my_class').show();// $('.my_class').show(3000);/*关于速度的关键字(字符串)fast: 快normal: 正常slow:慢可以通过以下方式修改内置的速度常量值jQuery.fx.speeds.fast = 毫秒值jQuery.fx.speeds.normal = 毫秒值jQuery.fx.speeds.slow = 毫秒值修改的时候注意作用域问题还可以通过这个方式自定义速度关键字jQuery.fx.speeds.myFast = 毫秒值*/// $('.my_class').show('slow');//还可以接受额外的参数,这个参数是回调函数$('.my_class').show('slow', function () {alert('动画执行完毕!');});});//hide$('input[value=hide]').click(function () {// $('.my_class').hide();// $('.my_class').hide(3000);jQuery.fx.speeds.fast = 5000;$('.my_class').hide('fast');});//toggle$('input[value=toggle]').click(function () {$('.my_class').toggle(2000);});//fadeIn$('input[value=fadeIn]').click(function () {$('.my_class').fadeIn(3000);});//fadeOut$('input[value=fadeOut]').click(function () {$('.my_class').fadeOut(3000);});//fadeToggle$('input[value=fadeToggle]').click(function () {$('.my_class').fadeToggle(3000);});//slideDown$('input[value=slideDown]').click(function () {$('.my_class').slideDown(3000);});//slideUp$('input[value=slideUp]').click(function () {$('.my_class').slideUp(3000);});//slideToggle$('input[value=slideToggle]').click(function () {$('.my_class').slideToggle(3000);});//animate$('input[value=animate]').click(function () {$('.my_class').animate({// left : "500px",left : "+=200",opacity : 0.25// background : 'blue' 颜色设置不了}, 5000, function () {alert("执行完毕");});});//stop$('input[value=stop]').click(function () {$('.my_class').stop();});//delay 接受一个参数,表示暂停多少毫秒之后继续执行$('input[value=delay]').click(function () {$('.my_class').fadeOut(2000).delay(2000).slideDown(2000);});});</script></body></html>
<!DOCTYPE html><html><head><meta charset="utf-8" /><title>作业</title><style type="text/css">*{ margin:0; padding:0;}body {font-size:12px;text-align:center;}a { color:#04D; text-decoration:none;}a:hover { color:#F50; text-decoration:underline;}.SubCategoryBox {width:600px; margin:0 auto; text-align:center;margin-top:40px;}.SubCategoryBox ul { list-style:none;}.SubCategoryBox ul li { display:block; float:left; width:200px; line-height:20px;}.showmore { clear:both; text-align:center;padding-top:10px;}.showmore a { display:block; width:120px; margin:0 auto; line-height:24px; border:1px solid #AAA;}.showmore a span { padding-left:15px; background:url(img/down.gif) no-repeat 0 0;}.promoted a { color:#F50;}</style><!-- 引入jQuery --><script src="../jquery/jquery-2.2.3.js"></script></head><body><div class="SubCategoryBox"><ul><li ><a href="#">佳能</a><i>(30440) </i></li><li ><a href="#">索尼</a><i>(27220) </i></li><li ><a href="#">三星</a><i>(20808) </i></li><li ><a href="#">尼康</a><i>(17821) </i></li><li ><a href="#">松下</a><i>(12289) </i></li><li ><a href="#">卡西欧</a><i>(8242) </i></li><li ><a href="#">富士</a><i>(14894) </i></li><li ><a href="#">柯达</a><i>(9520) </i></li><li ><a href="#">宾得</a><i>(2195) </i></li><li ><a href="#">理光</a><i>(4114) </i></li><li ><a href="#">奥林巴斯</a><i>(12205) </i></li><li ><a href="#">明基</a><i>(1466) </i></li><li ><a href="#">爱国者</a><i>(3091) </i></li><li ><a href="#">其它品牌相机</a><i>(7275) </i></li></ul><div class="showmore"><a href="#"><span>显示全部品牌</span></a></div></div><script type="text/javascript">$(function () {//1.获得要隐藏或显示的livar hideLi = $('.SubCategoryBox ul li:gt(5):not(:last)');//初始化隐藏lihideLi.css('display', 'none');//2、显示全部div的单机事件$('.showmore > a').get(0).onclick = function () {if ($('.showmore > a > span').text() == '显示全部品牌') {$('.showmore > a > span').text('隐藏部分品牌');//剩余的li显示出来hideLi.css('display', 'block');//改变图标$('.showmore > a > span').css('background', 'url(img/up.gif) no-repeat 0 0');//找到要变颜色的li// $('.SubCategoryBox ul li').filter(':eq(0),:eq(3),:eq(10)').addClass('promoted');//:contains("佳能") 查找包含佳能内容的元素$('.SubCategoryBox ul li').filter(':contains("佳能"),:contains("尼康"),:contains("奥林巴斯")').addClass('promoted');} else {$('.showmore > a > span').text('显示全部品牌');//剩余的li隐藏hideLi.css('display', 'none');//改变图标$('.showmore > a > span').css('background', 'url(img/down.gif) no-repeat 0 0');//找到要变色的li// $('.SubCategoryBox ul li').filter(':eq(0),:eq(3),:eq(10)').removeClass('promoted');$('.SubCategoryBox ul li').filter(':contains("佳能"),:contains("尼康"),:contains("奥林巴斯")').removeClass('promoted');}}});</script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>联动下拉菜单</title><style type="text/css"></style><script type="text/javascript" src="../jquery-2.2.3.min.js"></script><script type="text/javascript">$(function () {// 原生的JSON, data返回了是json格式, 需要反序列化为字面量对象: JSON.parse(data);// jQuery的getJSON()和ajax()方法返回的data为字面量对象$.getJSON('../jQuery专用.json', null, function (data) {// jQuery的each方法: each(idx,ele);// js原生的forEach方法: forEach(ele, idx, array/object);// ele: 数组中的每个省对象data.personInfos.forEach(function (ele, idx) {// 添加到left$('#left_sel').append('<option>' + ele.address +'</option>');// 添加到right// 未选择时显示所有人// 遍历每个省的人ele.persons.forEach(function (person) {// 添加name用filter来过滤$('#right_sel').append('<option name="'+ ele.address +'">' + person.name +'</option>');});// 用change事件, change事件应该加在select上,// 不能加在option上, 也不要在option上用click$('#left_sel').change(function(event) {var that = $(this);// 除了请选择以外, 全部清空$('#right_sel option').not(':first').remove();// 匹配省份动态显示人data.personInfos.forEach(function (ele, idx) {// 判断if (ele.address == that.val()) {ele.persons.forEach(function (person) {$('#right_sel').append('<option>'+ person.name +'</option>');});}});});});});}); // onload结束</script></head><body><select name="" id="left_sel"><option value="">请选择地区</option></select><select name="" id="right_sel"><option value="">请选择人</option></select></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>老师的手风琴的效果</title><style type="text/css">.menu_list{width: 150px;}.menu_head{height: 30px;line-height: 30px;cursor: pointer;background: orange;text-align: center;font-size: 20px;margin:10px 0 0;border-bottom: 3px solid orangered;border-radius: 5px 5px 0 0;}.menu_body{cursor: pointer;background: lightgreen;text-align: center;}.menu_body div{border-bottom: 2px solid red;}</style><script type="text/javascript" src="../jquery-2.2.3.min.js"></script></head><body><div class="menu_list"><!-- <div class="menu_head"></div><div class="menu_body"><div>内容1</div><div>内容2</div><div>内容3</div></div> --></div><!-- <div class="menu_list"><div class="menu_head"></div><div class="menu_body"><div>内容1</div><div>内容2</div><div>内容3</div></div></div><div class="menu_list"><div class="menu_head"></div><div class="menu_body"><div>内容1</div><div>内容2</div><div>内容3</div></div></div> --><script type="text/javascript">$(function () {$.getJSON("../jQuery专用.json", null, function (data) {data.personInfos.forEach(function (ele, idx) {$('.menu_list').append('<div class="menu_head">'+ele.address+'</div><div class="menu_body"></div');ele.persons.forEach(function (person) {$('.menu_body:last').append('<div>' + person.name + '</div>');});});// 折叠效果$('.menu_head').click(function(event) {// 点击展开或闭合,同时其他的body闭合$(this).next('div.menu_body').slideToggle().siblings('div.menu_body').slideUp();// 点击展开或闭合//$(this).next('div.menu_body').slideToggle();});});});</script></body></html>
/*遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)Iterator的遍历过程是这样的。(1)创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。(2)第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。(3)第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。(4)不断调用指针对象的next方法,直到它指向数据结构的结束位置。每一次调用next方法,都会返回数据结构的当前成员的信息。具体来说,就是返回一个包含value和done两个属性的对象。其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。*/// 可迭代的对象自身或原型链上,// 必须有一个Symbol.iterator属性, 通过这个属性就能获得迭代器var str = "abc";console.log(typeof str[Symbol.iterator]); // function// 调用迭代器var iterator = str[Symbol.iterator]();console.log(iterator.next()); // Object { value="a", done=false}console.log(iterator.next()); // Object { value="b", done=false}console.log(iterator.next()); // Object { value="c", done=false}console.log(iterator.next()); // Object { done=true, value=undefined} // 调用完成console.log(iterator.next()); // Object { done=true, value=undefined}var arr = ['你','们','好'];var iterator = arr[Symbol.iterator]();console.log(iterator.next().value); // 你console.log(iterator.next().value); // 们console.log(iterator.next().value); // 好console.log(iterator.next().value); // undefinedconsole.log(iterator.next().value); // Object { done=true, value=undefined}
// 大神的模拟function makeIterator(array) {var nextIndex = 0;return {next: function() {return nextIndex < array.length ?{value: array[nextIndex++], done: false} :{value: undefined, done: true};}};}
/*思路: 用数组存储数据, 下标的状态用闭包保存, 每次调用自增属性: value, done方法: next()返回值: 返回值应该是一个对象,对象中有next()方法闭包用在next()方法里,return { value=参1, done=布尔值};*/function myIterator(target) {// 传入的参数应该为数组或字符串if (! (typeof target == "string" || target instanceof Array)){console.log("TypeError : 数据类型不正确,请传入数组或字符串!!!");return ;}var idx = 0; // 会通过闭包保存在内存中var result = {};result.next = function () {var result1 = {};// 判断下标和长度的关系if (idx < target.length) {result1.value = target[idx++];result1.done = false;}else {result1.value = undefined;result1.done = true;}return result1;};return result;}console.group("判断测试");// number类型myIterator(1312414214);// Object类型var oo = {};myIterator(oo);console.groupEnd();console.group("字符串测试");var fn1 = myIterator("1314");var char1 = fn1.next();var char2 = fn1.next();var char3 = fn1.next();var char4 = fn1.next();var char5 = fn1.next();console.log(char1);console.log(char2);console.log(char3);console.log(char4);console.log(char5);console.log(char1.value);console.log(char2.value);console.log(char3.value);console.log(char4.value);console.log(char5.value);fn1 = null; // 释放闭包所占内存console.groupEnd();console.group("数组的测试");var fn2 = myIterator(["I", "MISS" , "U"]);var ele1 = fn2.next();var ele2 = fn2.next();var ele3 = fn2.next();var ele4 = fn2.next();var ele5 = fn2.next();console.log(ele1);console.log(ele2);console.log(ele3);console.log(ele4);console.log(ele5);console.log(ele1.value);console.log(ele2.value);console.log(ele3.value);console.log(ele4.value);console.log(ele5.value);fn1 = null; // 释放闭包所占内存console.groupEnd();
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>迭代器的深入讨论</title><script type="text/javascript">// 自定义的迭代器function idMaker(target) {var nextIndex = 0;if (!(typeof target =="string"|| target instanceof Array)){console.log("请传入数组或字符串");return;}return {next: function() {// 三目运算写法1//return nextIndex < target.length ?{value: target[nextIndex++], done: false} :{value: undefined, done: true};// 三目运算写法2return {value : target[nextIndex++],done: nextIndex < target.length ? false : true};}};}// 封装重复调用.next()的效果function idMakerCountObj(arrstr,count) {// 回调var fn = idMaker(arrstr);for (var i = 0; i < count ; i++) {console.log(fn.next());}}// 封装重复调用.next().value的效果function idMakerCountVal(arrstr,count) {var fn = idMaker(arrstr);for (var i = 0; i < count ; i++) {console.log(fn.next().value);}}// 调用idMakerCountObj(["I","MISS","U"],5);idMakerCountVal(["I","MISS","U"],5);//调用var str = "梦想决定你人生的上限, 而努力决定了你人生的下限! 人生无极限,努力吧!";idMakerCountVal(str,str.length);</script></head><body></body></html>
<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>闭包</title></head><body><script type="text/javascript">//函数嵌套,就是一个函数内部有另外一个函数function fn1 () {var num = 100;function subFn1 (num1) {console.log("num is " + (num + num1));console.log("我是一个嵌套函数的子函数。");}subFn1(50);}fn1();//可以把内部函数当做外部函数的返回值返回//这么做的好处是,我们可以在任何时候调用内部函数都行。//而且内部函数中引用的外部函数的变量,一直存在。function fn2 () {var num2 = 100;function subFn2 (param) {console.log("num2 is " + (num2 + param));}//subFn2是返回函数,subFn2()是返回运行结果return subFn2;}// console.log(fn2());//运行结果是fn2内部函数var resultFn2 = fn2();resultFn2(500);resultFn2(200);//自增操作 :可以证明其变量存在内存中,不会消失function fn3 () {var count = 0;// function subFn3 () {// console.log("count is " + (++count));// }// return subFn3;//一般都写匿名函数return function () {console.log("count is " + (++count));};}var resultFn3 = fn3();resultFn3();resultFn3();resultFn3();console.log("====================");//每次运行完外部函数,都会生成一个新的内部函数。var resultFn4 = fn3();resultFn4();resultFn4();console.log(resultFn3 === resultFn4);//需求:判断两个对象的任一属性值的大小var obj1 = {name : "a",age : 18};var obj2 = {name : "b",age : 15};//访问对象的属性不仅有(.)语法,还可以使用[]来访问console.log(obj1["name"]);console.log(obj1.age > obj2.age);//比较两个对象任意属性值大小//外部函数的参数是要比较的属性名字function comparePropertyFn (propertyName) {//返回内不函数,参数是要比较的两个对象return function (obj1, obj2) {//通过属性名字获得值var value1 = obj1[propertyName];var value2 = obj2[propertyName];//最后的判断if (value1 > value2) {return 1;} else if (value1 === value2) {return 0;} else {return -1;}};}//获得内部的比较函数//比较age属性值var resultCompareFn = comparePropertyFn("age");var resultValue = resultCompareFn(obj2, obj1);console.log(resultValue);//比较name属性值var resultCompareFn2 = comparePropertyFn("name");var resultValue2 = resultCompareFn2(obj2, obj1);console.log(resultValue2);</script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>js异步执行</title><script type="text/javascript">/*【异步执行】javascript的执行环境是"单线程",单线程是指一次只能运行一个任务.如果有多个任务,只能排队执行.【单线程的好处】实现简单【单线程的坏处】执行多个任务,如果前一个运行时间过长,或浏览器假死,后面的任务只能等待.【同步任务】一次只能执行一个任务【异步任务】把任务分成两部分 :--第一部分一般是请求数据(耗时操作),--第二部分一般是回调函数,这个回调函数包括了对外部数据的处理.第一部分执行完,不是立即调用第二部分, 而是将程序的执行权交给第二部分,然后第一部分的数据完全返回会, 才会执行第二部分的任务**所以** 异步任务执行顺序和任务排列无关!!【串行】 任务一个接一个执行【并行】 任务并列执行【串行和并行结合】设置一个条件,每次最多能并行n个任务, 这样可以避免性能的消耗【】【】【】【】【】*/// 模拟一个异步的任务// console.log("***********before***********");// setTimeout(function () {// console.log("***********ok***************");// },10);// console.log("***********after************");// 异步任务函数function asynFn (arg, callbackFn) {console.log("+++++++++++++" + arg +"++++++++++++++++++");setTimeout(function () {callbackFn(arg + 1000); // 一个参数},0);}// 调异步任务// asynFn(234,function (data) {// console.log(data);// });// 调用5个异步的任务// 串行任务,但是时间参数怎么控制的么// 调用的是异步任务函数// asynFn(1,function (data) { // 此处data为形参// // 参1: 返回的结果// asynFn(data,function (data) {// asynFn(data,function (data) {// asynFn(data,function (data) {// asynFn(data,function (data) {// // 运行下// });// });// });// });// });/*************串行改进********************/// // 编写一个串行函数// // 串行函数的参数// var items = [1, 2, 3, 4, 5];// // 每个异步任务返回结果的数组// var results = [];// // 串行函数// function series (item) {// if (item){// // 开始调用异步任务// asynFn(item, function (result) {// // 把回调函数的返回值存储在最终结果数组中// results.push(result);// return series(items.shift());// });// } else {// //console.log(results);// finalFn(results); // 最终结果打印函数// }// }// finalFn完成函数function finalFn (x) {console.log(x);}// // 调用串行函数// // shift()弹出首个元素,并返回该元素// series(items.shift());/*************串行改进_End********************//*************并行函数********************/// 参数数组// var items = [1, 2 ,3 ,4 ,5];// //返回的结果数组// var results = [];// //// items.forEach(function (item) {// // 调用异步任务// asynFn(item,function (result) {// // 添加到结果数组// results.push(result);// // 结果一起执行// // 数据一起返回// if (results.length == items.length) {// // 打印// finalFn (results);// }// });// });/*************并行执行_End********************//*************串行+并行的结合********************//*因为:异步任务执行顺序和任务排列无关running++ 会运行在running--的后面*/// 参数数组var items = [1, 2 ,3 ,4 ,5];//返回的结果数组var results = [];// 当前运行的任务数量var running = 0;// 每次最大任务数量var limit = 2;// 串行、并行函数function run () {// 循环为并行while (running < limit && items.length > 0) {// 调用异步任务asynFn(items.shift(),function (result) {// 存到结果数组中results.push(result);// 当前任务数量自减// 测试console.log("我是callbackFn");running--; // 写在了回调函数里, 任务结束了才自减if (items.length > 0) {// 调用runrun(); // 此处为串行} else if(running === 0) {finalFn(results);}});// 每次循环当前数量++console.log("测试在callbackFn前面执行,running++");running++;}}// 调用run();/*************串行+并行的结合_End********************//*ajax本身就是异步请求,所以画UI和绑定事件都应该写在callback函数内写外边会出现错误*/</script></head><body></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>模块化</title><script type="text/javascript">/*【模块化】: 是一种思想,按分类思想分包或分类管理.(理解成文件夹)随着网站内容丰富和复杂,简单的用<script>标签导入外部的JS文件不能适应现代开发了,我们需要团队协作, 分离模块, 模块测试等复杂的需求模块化是指在解决一个问题或一系列问题时, 按照一种分类的思想对功能进行分解处理.模块化对于软件来说, 可以解耦软件的复杂性.【耦合度】: 即为相关联性, 耦合度越低越好.模块化是java和php等后端语言的必须得思想;分包管理或分文件管理【模块化设计必须有的能力】1. 定义封装的模块.2. 定义对新模块的依赖性.3. 可以引入其他的模块.【模块化开发需要遵循规范AMD或CMD等】【模块化思想】函数也算是模块对象也是只不过没按照模块化规范来写*/// 一. 函数写法 函数本身算一个模块// 缺点:// 1.污染了全局变量, 模块之间无法保证命名是否冲突和覆盖// 2. 模块之间没有直接关系// 二. 对象写法 对象本身算一个模块// 优点:// 1. 解决了函数写法的缺点// 2. 所有的成员打包放在了这个对象中// 缺点:// 1. 可以对该模块内部的属性// 三.函数立即调用// 不暴露成员变量的目的 (命名空间)// 1. 闭包思想// 2. 优点: 外部无法修改内部的局部变量.// 四. 放大模式////// 五. 无关放大模式////////var obj1 = {name : "王大可",m1 : function () {console.log("m1:" + this.name);},m2 : function () {console.log("m2:" + this.name);}};obj1.m1();obj1.name ="撼地神牛";obj1.m1();// 三.函数立即调用//1.不暴露成员变量的目的 (命名空间)var modal = (function () {var age =18;var m1 = function () {return "m1: " + age;};var m2 = function () {age++;return "m2: " + age;};return {//"m1" : m1(), // modal.m1 是属性// 把函数的指针作为value// key m1是属性, value m1是上面的变量保存的函数地址// key m1 实际是"m1"m1 : m1, // modal.m1() 是方法m2 : m2 // modal.m2() 是方法};})();console.log(modal.m1);console.log(modal.m1());console.log(modal.m2());console.log("这也是闭包");console.log(modal.m1());console.log("++++++以下用了闭包+++++++");var fn = modal.m2;console.log(fn());console.log(fn());console.log(fn());console.log(fn());console.log(fn());// 四. 放大模式// 模块化的思想给对象添加了一个方法var modal4 = {};modal4 = (function (mod) {mod.m1 = function () {console.log("被放大了, 额外添加的方法");};return mod;})(window.modal4); // 传实际的参数,写modal4也可以modal4.m1();// 五. 无关放大模式var modal5 = {};modal5 = (function (mod) {mod.m1 = function () {console.log("被放大了, 额外添加的方法");};return mod;})(window.modal5 || {});modal5.m1();</script></head><body></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>RequireJS</title><script type="text/javascript">/*【RequireJS概念】1. RequireJS是一个前端模块化的管理工具库.【RequireJS基本思想】通过一个函数将所需的模块实现装载进来. 然后返回一个新的函数 (模块).所有的业务逻辑代码, 都会放在这个函数内部操作【如何使用RequireJS】去官网下载, 然后通过<script> 中src属性引用【RequireJS相应的API】见demo【】【】*/</script><!-- <script type="text/javascript" src="js/sayHello.js"></script> --><script type="text/javascript" src="require.js"></script><script type="text/javascript">// requireJS的基本API/*require有三个变量: define, require, requirejsrequire和requirejs是一个意思, 我们一般使用requiredefine : 定义模块require : 加载模块的, 并且可以执行加载模块后的回调函数符合AMD标准: 异步加载模块*/// 利用require来加载模块 (异步加载)// 数组用来加载多个模块//require(['js/SayHello']);// 有回调函数// require(['js/SayHello'],function () {// alert("加载完成!");// })// 加载配置文件// 上面例子是加载本地文件// 也可以加载网络文件或服务器文件, 这样就不能用上述方式加载// 需要用require.config来配置一下 (没有远端环境也可以自己配置, 强大!!!)// 省略.js// 百度的jQuery库: http://libs.baidu.com/jquery/1.9.0/jquery.min.js// require.config({// paths : {// jquery : ["http://libs.baidu.com/jquery/1.9.0/jquery.min"]// }// });// // 使用配置中的参数// // $必须实参传入// require(['jquery'],function ($) {// $(function () {// // 可以使用jQuery语法了// });// })// require.config配置路径,首先可以访问非本地的模块// 我们也可以把本地,模块也利用config来配置, 简化开发// 而且服务器的模块和本地的模块可以配合使用,// 比如服务器端的jQuery文件失效,就可以从本地访问jQuery,反之亦然.// 省略.jsrequire.config({paths : {jquery : ["http://libs.baidu.com/jquery/1.9.0/jquery.min","jquery-2.2.3"],say : ["js/sayHello"],obj : ["js/obj"],person : ["js/Person"]}});// 使用配置中的参数// $必须实参传入// 没有返回值的放后面,say放最后require(['jquery','obj','person','say'],function ($,obj,Person) {$(function () {// 可以使用jQuery语法了alert("加载完成! ");alert(obj.name+"+++++"+obj.age);var xiaoming = new Person.Person("小雪",18);xiaoming.say();});})</script><style type="text/css">.my_div{width: 300px;height: 300px;background: red;}</style></head><body><div class="my_div"></div></body></html>
// Person.jsdefine(function () {var Person = function (name , age) {this.name = name;this.age = age;}Person.prototype.say = function() {alert("我叫: "+this.name+"年龄: "+this.age);};return {Person : Person}});
// sayHello.js// function fn () {// alert("你好啊!!!");// }// fn();// 定义模块 : define是一个全局变量 (函数)define(function () {function fn () {alert("你好啊!!!");}fn();});
// obj.jsdefine(function () {return {name : "小雪",age : 18};});
一 JS中的变量和属性有共同点, 可以类比1. 变量可以存放基本类型和引用类型;Eg ./*=======存放基本类型========*/var x1 = 123;var x2 = "I MISS U";/*=======存放引用类型(指针)========*/var x3 = [];var x4 = {};var x4 = function () {} // 就是传说中的函数表达式(匿名函数)2. 属性也可以存放基本类型和引用类型的值Eg ./*=======存放基本类型========*/var obj = {}; // 一个空的字面量对象obj.x1 = 123;obj.x2 = "I MISS U";/*=======存放引用类型(指针)========*/obj.x3 = [];obj.x4 = {};obj.x5 = function () {}; // 此时就是"方法"二: 属性的特点属性是属于某个对象的, 通过"."或 "[]"语法来调用同时, 属性实际是字符串类型的var prop1 = 123; // 一个变量初始化var testObj = {};testObj.prop1 = "测试"; // 变量名和属性一样??// 验证其实不一样console.log(testObj.prop1); // 测试console.log(prop1); // 123// 上面说明变量名和属性重名没有被覆盖. 其实没有任何关系// 其实本质属性是字符串console.log(testObj["prop1"]); // 测试// 说明属性确实是字符串//再来看老师下午所讲的, 就能解释通 m1 : m1 , 这么写是合理的var modal = (function () {var age =18;var m1 = function () {return "m1: " + age;};var m2 = function () {age++;return "m2: " + age;};return {//"m1" : m1(), // modal.m1 是属性// 把函数的指针作为value// key m1是属性, value m1是上面的变量保存的函数指针// key m1 实际是"m1"m1 : m1, // modal.m1() 是方法m2 : m2 // modal.m2() 是方法};})();
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>同源政策</title><script type="text/javascript">/*【同源政策】1995年, 同源政策被引入到浏览器中, 目前所有的浏览器都适用这种政策.同源政策最初的含义是: A页面的cookie, B页面不能读取到A页面的cookie, 除非这两个页面是"同源"【同源必须保证"三"相同】1. 协议相同2. 域名相同3. 端口相同eg. http://www.ilovedota.com/dir/index.html协议: http://IP地址: 192.168.0.163域名: www.baidu.comDNS: Domain Name System,域名系统端口: port 端口是在域名后面用冒号 ":" 写例如: :8080(默认端口,省略)有get请求的完整网址 : http://wwww.liu.com:8080/dir/index.html?username="sdfasd"&password="*****"端口可分为虚拟端口和物理端口,其中虚拟端口指计算机内部或交换机路由器内的端口,不可见。例如计算机中的80端口、21端口、23端口等。物理端口又称为接口,是可见端口,计算机背板的RJ45网口,交换机路由器集线器等RJ45端口测试:1. http://www.ilovedota.com/dir/index.html2. http://www.ilovedota.com/other/other.html1和2是同源的,因为协议相同, 域名(IP地址)相同, 端口相同(都是默认的:8080端口)3. https://www.ilovedota.com/other/other.html // 不同源,协议不同4. http://www.ilove.com/other/other.html // 不同源,域名不同5. http://www.ilovedota.com:2024/other/other.html // 不同源,端口不同【同源的意义】保证用户信息的安全, 防止恶意网站窃取用户数据【同源政策能限制的范围】1. cookie 无法获取2. DOM无法获取3. ajax无法发送请求 (?为嘛要限制它)// 能发送请求访问数据就肯能窃取信息// 多个项目在多个服务器间存在信息请求交换怎么办??// 服务器端解决方案(了解)1. 架设代理服务器2. 浏览器请求同源服务器3. 然后再让同源服务器去请求其他服务器【JSONP】JSONP概念: JSONP是JSON的一种使用模式, 可以使用网站达到跨域的功能.【JSONP的流程】1、客户端访问: www.liu.com:8080/dir/index.html?jsoncallback=callbackFn2、假设访问后想返回的数据是: {"name" : "liu", "age" : 18};3、JSONP实际上返回的是callbackFn{"name" : "liu", "age" : 18}返回的不是json格式的数据, 而是一个代码段【JSONP的实现】1、通过script中的 src="在这里传"2、jQuery实现, 见demo【CORS (了解)】【WebSoket (了解)】*/</script></head><body><!--【JSONP的流程】1、客户端访问: www.liu.com:8080/dir/index.html?jsoncallback=callbackFn2、假设访问后想返回的数据是: {"name" : "liu", "age" : 18};3、JSONP实际上返回的是callbackFn{"name" : "liu", "age" : 18}返回的不是json格式的数据, 而是一个代码段-->// 一. script的src实现// 支持JSONP就可以用<script>function callbackFn (data) {// 返回data// 可以进行解析}</script><script type="text/javascript"></script><script type="text/javascript" src="http://liu.com:8080/index.html?jsoncallback=callbackFn"></script>// 二. jQuery的实现<script>$.getJSON("get","http://liu.com:8080/index.html?jsoncallback=?",function (data) {// 进行解析});</script></body></html>
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>匿名函数与callback深入思考</title><script>// 函数的三大特点:// 声明, 实现, 调用// 练习callback// 其实就是把函数作为参数传递// 实际传的是函数的地址function fn (x,y) {console.log(x+y(x));}function fn1 (x) {if (x<10) {return "我是传了参数的回调函数" +x;} else{return "我是窜了参数的" + x;}}fn(2,fn1);// ajax中成功的回调函数// 在函数的内部整理出了结果, 传入回调函数中, 在回调函数内能使用//// 匿名函数的传参调用(function (x) {console.log("我是匿名函数传了参"+ x);})(100000);// 函数内部的回调函数// 模拟ajax// function test (x,successCallbackFn) {// x +="wo ";// x +="爱你";// x += "一万年";// successCallbackFn(x); // 这里的x是实参,也可以successCallbackFn("我这的就只是实参");// return "\"我是返回值猜猜看\"";// }// test(1314,function (y) {// console.log(y);// })// 等价于function test2 (x) {x +="wo ";x +="爱你";x += "一万年";// (function(x){// console.log(x);// })("调用里传的是实际的参数");(function(){console.log(arguments[0]);})("调用里传的是实际的参数");return "\"我是返回值猜猜看\"";}test2(1314);</script></head><body></body></html>