首页 > 开发 > JAVA > 正文

菜鸟教程js学习笔记记录2

2016-07-25 21:44:50  来源:慕课网
<script>function myFunction(){var x;var d=10;switch (d) { case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="星期二"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break; case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break; default : x="自由时间"; }document.getElementById("demo").innerHTML=x;}</script><script>cars=["BMW","Volvo","Saab","Ford"];for(var i=0;i<cars.length;i++){document.write(cars[i]+"<br/>")}</script><script>cars=["BMW","Volvo","Saab","Ford"];for (var i=0,len=cars.length;i<len;i++){document.write(cars[i] + "<br>");}</script><script>function myFunction(){var x;var txt="";var person={fname:"Bill",lname:"Gates",age:56}; //数组的形式记录for(x in person){ txt+=","+person[x];}document.getElementById("demo").innerHTML=txt;}</script><script>function myFunction(){var x="",i=0;while(i<5){ document.write("今天是"+i+"</br>"); i++}document.getElementById("demo").innerHTML=x;}</script><script>function myFunction(){var x="",i=0;do{document.write("0数到100,"+i+"</br>"); i++;}while(i<=100)document.getElementById("demo").innerHTML=x;}</script><script>cars=["BMW","Volvo","Saab","Ford"];var i=0; //当car[]不为空时while(cars[i]){document.write(cars[i] + "<br>");i++;}</script><script>cars=["BMW","Volvo","Saab","Ford"];var i=0; //当car[]不为空时while(cars[i]){document.write(cars[i] + "<br>");i++;}</script><script>cars=["BMW","Volvo","Saab","Ford"];var i=0;for(;cars[i];){document.write(cars[i] + "<br>");i++;}</script><script>cars=["BMW","Volvo","Saab","Ford"];tag:{document.write(cars[0] + "<br>"); document.write(cars[1] + "<br>"); document.write(cars[2] + "<br>"); document.write(cars[3] + "<br>"); document.write(cars[4] + "<br>"); break tag; //跳出标签代码块document.write(cars[5] + "<br>"); }</script><script>document.getElementById("demo").innerHTML = typeof "string" + "<br>" + typeof 4.12 + "<br>" +typeof false + "<br>" +typeof [1,2,3,4] + "<br>" +typeof {name:"yq",sex:"man"}</script>//在 JavaScript 中 null 表示 "什么都没有"。//null是一个只有一个值的特殊类型。表示一个空对象引用//用 typeof 检测 null 返回是object。<script>var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};var person = null;document.getElementById("demo").innerHTML = typeof person;</script>Undefined在 JavaScript 中, undefined 是一个没有设置值的变量。typeof 一个没有值的变量会返回 undefined<script>var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};var person = undefined;document.getElementById("demo").innerHTML = typeof person;</script><script>document.getElementById("demo").innerHTML =// 类型typeof undefined + "<br>" +typeof null + "<br>" +//类型 值是否相等(null === undefined) + "<br>" +(null == undefined);</script><script>document.getElementById("demo").innerHTML =//类型typeof undefined + "<br>" +typeof null + "<br>" +// 值和类型相等(null === undefined) + "<br>" +(null == undefined);</script><script>document.getElementById("demo").innerHTML = typeof "john" + "<br>" + typeof 3.14 + "<br>" +//数字 typeof NaN + "<br>" +// boolean typeof false + "<br>" + typeof [1,2,3] + "<br>" + typeof {name:"yq",sex:"man"} + "<br>" +//object typeof new Date() + "<br>" +//函数 typeof function d(){} + "<br>" +//undefined typeof myCar + "<br>" +//object typeof null;</script>// 构造函数<script>document.getElementById("demo").innerHTML = "john".constructor + "<br>" + (3.14).constructor + "<br>" + false.constructor + "<br>" + [1,2,3,4].constructor + "<br>" + {name:'john', age:34}.constructor + "<br>" + new Date().constructor + "<br>" + function() {}.constructor</script><script>var fruits = ["1","2","3"];document.getElementById("demo").innerHTML = isArray(fruits);function isArray(myArray){ alert(myArray.constructor.toString()); //构造方法是否包含 Array return myArray.constructor.toString().indexOf("Array")>-1;}</script>//转为字符串 如果是减法转为整数"5" + 1 // 返回 "51" because 1 is converted to "1" "5" - 1 // 返回 4 because "5" is converted to 5<script>function myFunction() { var y = "John"; var x = + y; //如果变量不能转换,它仍然会是一个数字,但值为 NaN (不是一个数字): document.getElementById("demo").innerHTML = typeof x + "<br>" + x;}</script>function myFunction() { var str = "Visit W3cSchool!"; var n = str.search(/w3cschool/i); //搜索忽略大小写 document.getElementById("demo").innerHTML = n;}<script>//search 方法可使用字符串作为参数。字符串参数会转换为正则表达式:function myFunction() { var str = "Visit W3cSchool!"; var n = str.search("W3cSchool"); document.getElementById("demo").innerHTML = n;}</script>function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace(/Microsoft/i,"java"); document.getElementById("demo").innerHTML = txt;}<script>function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace("Microsoft","W3cSchool"); document.getElementById("demo").innerHTML = txt;}</script><script>function myFunction() { var str = document.getElementById("demo").innerHTML; var txt = str.replace("Microsoft","java"); document.getElementById("demo").innerHTML = txt;}</script><script> var r=new RegExp("e"); document.write(r.test("abcde"));</script><script>var patt1=new RegExp("e");document.write(patt1.test("The best things in life are free")+"</br>");document.write(/e/.test("abcd"));</script><script>var patt1=new RegExp("e");document.write(patt1.exec("The best things in life are free")+"</br>"); document.write(/a/.test("abcde"));</script><script>var txt="";function message(){ try { adddlert("Welcome guest!"); } catch(err) { txt="本页有一个错误。\n\n";//打印错误信息 txt+="错误描述:" + err.message + "\n\n"; txt+="点击确定继续。\n\n"; alert(txt); }}</script><script>function myFunction(){//自定义的异常,只需要err try{ var num=document.getElementById("demo").value; if (num=="") throw "不能为空"; if (isNaN(num)) throw "请输入数字"; if( num >10 ) throw "太大"; if(num <5) throw "太小"; }catch(err){ document.getElementById("mess").innerHTML="错误:"+err; }}</script><p>开启调试工具,在代码执行到第三行前会停止执行。</p><script>var x = 15 * 5;//f12开启调试debugger;document.getElementById("demo").innerHTML = x;</script>JavaScript 中,函数及变量的声明都将被提升到函数的最顶部。JavaScript 中,变量可以在使用后声明,也就是变量可以先使用再声明。x = 5; // 变量 x 设置为 5elem = document.getElementById("demo"); // 查找元素 elem.innerHTML = x; // 在元素中显示 xvar x; // 声明 xJavaScript 只有声明的变量会提升,初始化的不会。<h1>使用 "use strict":</h1><h3>不允许使用为定义的变量。</h3><p>浏览器按下 F12 开启调试模式,查看报错信息。</p><script>"use strict";x = 3.14; // 报错 (x 未定义)</script>这种错误经常会在 switch 语句中出现,switch 语句会使用恒等计算符(===)进行比较:以下实例会执行 alert 弹窗:var x = 10;switch(x) { case 10: alert("Hello");}<script> //JavaScript 中的所有数据都是以 64 位浮点型数据(float) 来存储。//所有的编程语言,包括 JavaScript,对浮点型数据的精确度都很难确定:var x = 0.1;var y = 0.2;var z = x + y;document.getElementById("demo").innerHTML = z;</script><script> //可以用整数的乘除法来解决:var x = 0.1;var y = 0.2;var z = (x * 10 + y *10) / 10;document.getElementById("demo").innerHTML = z;</script>function myFunction(a) { var power = 10; return; // 分号结束,返回 undefined a * power;}<p>如果你使用名字作为索引,当访问数组时, JavaScript 会把数组重新定义为标准对象,数组的方法及属性将不能再使用, 否则会产生错误:。</p><p id="demo"></p><script>var person = [];person["firstName"] = "John";person["lastName"] = "Doe";person["age"] = 46; document.getElementById("demo").innerHTML =person[0] + " " + person.length;</script>在 JavaScript 中, null 用于对象, undefined 用于变量,属性和方法。对象只有被定义才有可能为 null,否则为 undefined。如果我们想测试对象是否存在,在对象还没定义时将会抛出一个错误。错误的使用方式:if (myObj !== null && typeof myObj !== "undefined") 正确的方式是我们需要先使用 typeof 来检测对象是否已定义:if (typeof myObj !== "undefined" && myObj !== null) 在每个代码块中 JavaScript 不会创建一个新的作用域,一般各个代码块的作用域都是全局的。以下代码的的变量 i 返回 10,而不是 undefined:<head><script> function validateForm(){ var con=document.forms["myForm"]["fname"].values; if(con==null con==""){ alert("用户名必须输入"); return false; } }</script></head><body><form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">姓: <input type="text" name="fname"><input type="submit" value="提交"></form></body><script>function validateForm(){ var em=document.forms["myForm"]["email"].value; var a=em.indexOf("@"); var b=em.lastIndexOf("."); alert(b+","+em.length);//@不能为开头,至少空格两位,最后长度至少三位 if(a<1 a<b-2 b+2>=em.length){//错误情况进入的 alert("请输入合法的邮箱格式"); return false; }} </script></head><body><form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">Email: <input type="text" name="email"><input type="submit" value="Submit"></form><script> 数据为 键/值 对。数据由逗号分隔。大括号保存对象方括号保存数组 var text='{"employees":[{"firstName":"yq",'+ '"lastName":"yq"},{"firstName":"yq1","lastName":"yq1"}]}';//转换obj = JSON.parse(text);document.getElementById("demo").innerHTML =obj.employees[1].firstName + " " + obj.employees[1].lastName;</script><body> <a href="javascript:void(0)" rel="external nofollow" >单此处什么也不会发生</a></body> //alert不用加封号<p>点击以下链接查看结果:</p><a href="javascript:void(alert('hello'));" rel="external nofollow" >点我!</a><script> //数据为 键/值 对。//数据由逗号分隔。//大括号保存对象//方括号保存数组 var text='{"employees":[{"firstName":"yq",'+ '"lastName":"yq"},{"firstName":"yq1","lastName":"yq1"}]}';//转换obj = JSON.parse(text);document.getElementById("demo").innerHTML =obj.employees[1].firstName + " " + obj.employees[1].lastName;</script><script type="text/javascript"><!--function getValue(){ var a,b,c; //中断运行 b= void (a=1,c=2); document.write('a = ' + a + ' b = ' + b +' c = ' + c );}//--># 包含了一个位置信息,默认的锚是#top 也就是网页的上端。而javascript:void(0), 仅仅表示一个死链接。在页面很长的时候会使用 # 来定位页面的具体位置,格式为:# + id。如果你要定义一个死链接请使用 javascript:void(0) 。</script><a href="javascript:void(0);" rel="external nofollow" >点我没有反应的!</a> <a href="#pos" rel="external nofollow" >点我定位到指定位置!</a> <p id="pos">尾部定位点</p>使用简洁的格式载入 JavaScript 文件 ( type 属性不是必须的):<script src="myscript.js" rel="external nofollow" >分号是用来分隔可执行JavaScript语句。 由于函数声明不是一个可执行语句,所以不以分号结束。<script> //在函数表达式存储在变量后,变量也可作为一个函数使用:var x = function (a, b) {return a * b};document.getElementById("demo").innerHTML = x(4,5);</script><script> //函数同样可以通过内置的 JavaScript 函数构造器(Function())定义。var myFunction =new Function("a","b","return a*b;");document.getElementById("demo").innerHTML = myFunction(4, 4);</script>在 JavaScript 中,很多时候,你需要避免使用 new 关键字。在之前的教程中我们已经了解了 "hoisting(提升)"。提升(Hoisting)是 JavaScript 默认将当前作用域提升到前面去的的行为。提升(Hoisting)应用在变量的声明与函数的声明。因此,函数可以在声明之前调用<script>//函数自调用 (function(){ document.getElementById("demo").innerHTML = "Hello! 我是自己调用的"; })();</script><p> arguments.length 属性返回函数接收到参数的个数:</p><p id="demo"></p><script>function myFunction(a, b) { return arguments.length;}document.getElementById("demo").innerHTML = myFunction(4, 3);</script></body>函数定义作为对象的属性,称之为对象方法。函数如果用于创建新的对象,称之为对象的构造函数。<script>function myFunction(x, y) { if(y==undefined){ y=0; } return x * y;}document.getElementById("demo").innerHTML = myFunction(4);</script><p>设置函数参数默认值。</p><p id="demo"></p><script>function myFunction(x, y) { //如果没有则为0 y=y0;如果y已经定义 , y 返回 y, 因为 y 是 true, 否则返回 0, 因为 undefined 为 false。 return x * y;}document.getElementById("demo").innerHTML = myFunction(4);</script><script>function findMax() {var i,max=0; //通过内置对象查找最大值 for(var i=0;i<=arguments.length;i++){ if(arguments[i]>max){ max=arguments[i] } } return max;} document.getElementById("demo").innerHTML = findMax(4, 5, 6);</script><script>function sumAll() { var i, sum = 0; for(var i=0;i<arguments.length;i++){ sum+=arguments[i]; } return sum;} document.getElementById("demo").innerHTML =sumAll(1, 123, 500, 115, 44, 88);</script>一般而言,在Javascript中,this指向函数执行时的当前对象。以上函数不属于任何对象。但是在 JavaScript 中它始终是默认的全局对象。在 HTML 中默认的全局对象是 HTML 页面本身,所以函数是属于 HTML 页面。在浏览器中的页面对象是浏览器窗口(window 对象)。以上函数会自动变为 window 对象的函数。myFunction() 和 window.myFunction() 是一样的:<script>function myFunction() { return this;} // 在全局函数是一个 window 对象。document.getElementById("demo").innerHTML = myFunction(); </script><script>var myObject ={ name:"yq", sex:"man", fullName:function(){ return this.name+","+this.sex; }}document.getElementById("demo").innerHTML = myObject.fullName(); </script><script>function myFunction(arg1, arg2) { this.firstName=arg1; this.lastName=arg2;}var x = new myFunction("John","Doe")document.getElementById("demo").innerHTML = x.firstName; </script>function myFunction(a, b) { return a * b;}myFunction.call(myObject, 10, 2); // 返回 20function myFunction(a, b) { return a * b;}myArray = [10,2];myFunction.apply(myObject, myArray); // 返回 20call() 和 apply() 是预定义的函数方法。 两个方法可用于调用函数,两个方法的第一个参数必须是对象本身。<script> //函数可以访问定义在函数外的变量:var a = 4;function myFunction() { document.getElementById("demo").innerHTML = a * a;} </script>变量声明是如果不使用 var 关键字,那么它就是一个全局变量,即便它在函数内定义。实际上,在 JavaScript 中,所有函数都能访问它们上一层的作用域。JavaScript 支持嵌套函数。嵌套函数可以访问上一层的函数变量。该实例中,内嵌函数 plus() 可以访问父函数的 counter 变量:<script>document.getElementById("demo").innerHTML = add(); function add(){ var counter =0; function plus(){ counter+=2; } plus(); return counter; }</script>闭包是可访问上一层函数作用域里变量的函数,即便上一层函数已经关闭。<script>var x=document.getElementById("main");var y=x.getElementsByTagName("p");document.write('id="main"元素中的第一个段落为:' +y[0].innerHTML);</script<script>x=document.getElementsByClass("intro");document.write("<p>文本来自 class 为 intro 段落: " + x[0].innerHTML + "</p>");</script><p><b>注意:</b>Internet Explorer 8 及更早 IE 版本不支持 getElementsByClassName() 方法。</p></body>绝对不要在文档加载完成之后使用 document.write()。这会覆盖该文档。<script>//属性 驼峰命名document.getElementById("p2").style.color="blue";document.getElementById("p2").style.fontFamily="Arial";document.getElementById("p2").style.fontSize="larger";</script><p id="p1">这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。 这是一个文本。</p><input type="button" value="隐藏文本" onclick="document.getElementById('p1').style.visibility='hidden'" /><input type="button" value="显示文本" onclick="document.getElementById('p1').style.visibility='visible'" /><script>function checkCookies(){ //cookie是否可用if (navigator.cookieEnabled==true) { alert("Cookies 可用") }else { alert("Cookies 不可用") }}</script><h1 onmouseover="style.color='red'"onmouseout="style.color='black'">将鼠标移至文部上</h1><script>function myFunction(x){//背景颜色x.style.background="yellow";}</script></head><body>输入你的名字: <input type="text" onfocus="myFunction(this)"><p>当输入框获取焦点时,修改背景色(background-color属性) 将被触发。</p><script>function lighton(){document.getElementById('myimage').src="bulbon.gif" rel="external nofollow" ;}function lightoff(){document.getElementById('myimage').src="bulboff.gif" rel="external nofollow" rel="external nofollow" ;}</script></head><body><img id="myimage" onmousedown="lighton()" onmouseup="lightoff()" src="bulboff.gif" rel="external nofollow" rel="external nofollow" width="100" height="180" /><p>点击不释放鼠标灯将一直亮着!</p><p>点击按钮执行 <em>displayDate()</em> 函数.</p><button id="myBtn">点这里</button><script>//js添加事件document.getElementById("myBtn").onclick=function(){displayDate();};function displayDate(){document.getElementById("demo").innerHTML=Date();}</script><script>function changetext(id){id.innerHTML="yq";}</script></head><body><h1 onclick="changetext(this)">点击文本!</h1></body>function myFunction(){var x=document.getElementById("fname");x.value=x.value.toUpperCase();}</script></head><body>输入你的名字: <input type="text" id="fname" onchange="myFunction()"><p>当你离开输入框后,函数将被触发,将小写字母转为大写字母。</p><script>document.getElementById("myBtn").addEventListener("click",displayDate);function displayDate() { document.getElementById("demo").innerHTML = Date();}</script>在 冒泡 中,内部元素的事件会先被触发,然后再触发外部元素,即: <p> 元素的点击事件先触发,然后会触发 <div> 元素的点击事件。在 捕获 中,外部元素的事件会先被触发,然后才会触发内部元素的事件,即: <div> 元素的点击事件先触发 ,然后再触发 <p> 元素的点击事件。<script>var x = document.getElementById("myBtn");x.addEventListener("click", myFunction);x.addEventListener("click", someOtherFunction);function myFunction() { alert ("Hello World!")}function someOtherFunction() { alert ("函数已执行!")}</script><script>var x = document.getElementById("myBtn");x.addEventListener("mouseover", myFunction);x.addEventListener("click", mySecondFunction);x.addEventListener("mouseout", myThirdFunction);function myFunction() { document.getElementById("demo").innerHTML += "Moused over!<br>"}function mySecondFunction() { document.getElementById("demo").innerHTML += "Clicked!<br>"}function myThirdFunction() { document.getElementById("demo").innerHTML += "Moused out!<br>"}</script><p>尝试重置浏览器的窗口触发 "resize" 事件句柄。</p><p id="demo"></p><script>window.addEventListener("resize", function(){ document.getElementById("demo").innerHTML = Math.random();});</script><div id="myDIV"> div 元素添加了 onmousemove 事件句柄,鼠标在桔红色的框内移动时会显示随机数。 <p>点击按钮移除 DIV 的事件句柄。</p> <button onclick="removeHandler()" id="myBtn">点我</button></div><p id="demo"></p><script>document.getElementById("myDIV").addEventListener("mousemove", myFunction);function myFunction() { document.getElementById("demo").innerHTML = Math.random();}function removeHandler() { document.getElementById("myDIV").removeEventListener("mousemove", myFunction);}</script><script>var x = document.getElementById("myBtn"); //如果对象不为空,则使用add if(x.addEventListener){ x.addEventListener("click",myFunction); }else if(x.attachEvent){ x.attachEvent("onclick",myFunction); }function myFunction() { alert("Hello World!");}</script><script> //新建元素 var p2=document.createElement("p1"); //新建文本节点 var n1=document.createTextNode("添加的内容"); //添加内容 p2.appendChild(n1); var ele=document.getElementById("div1"); //追加子节点 ele.appendChild(p2);</script><div id="div1"> <p id="p1">这是一个段落。</p> <p id="p2">这是另一个段落。</p></div><script>var parent=document.getElementById("div1");var child=document.getElementById("p2"); //删除孩子parent.removeChild(child);</script><script>var parent=document.getElementById("div1");var child=document.getElementById("p1"); parent.removeChild(child);//获取父亲再删除儿子child.parentNode.removeChild(child);</script><script>var person=new Object(); person.sex="girl";person.firstname="John";person.lastname="Doe";person.age=50;person.eyecolor="blue"; document.write(person.firstname + " is " + person.age + " years old."+person.sex);</script>