JavaSpcript编程(八)
1、往文档中显示一句话
<title></title>
<script>
/*往文档中显示一句话*/
document.write("hello js");
</script>
2、js是客户端脚本语言
<!--js是客户端脚本语言-->
<h1>aaaaaaaaaaaaaaaaa</h1>
<p>bbbbbbbbbbbbbbbbb</p>
3、在事件中引入js脚本
<!--在事件中引入js脚本-->
<input type="button" value="OK"
onclick="alert('Hello');" />
4、伪URL地址引入js脚本
<!--伪URL地址引入js脚本-->
<a href="javascript:alert('Hello');">点击我...</a>
5、通过script标签引入js脚本
<!--通过script标签引入js脚本-->
<script>
/*往文档中显示一句话*/
document.write("<h1>hello world</h1>");
</script>
6、定义局部变量用var关键字
获取变量的数据类型
// 定义局部变量用var关键字
var name = "小明"; /*字符数据用单引号或双引号引起来*/
var gender = "男",age = 18;
var code;
var isStudent=true;
// 获取变量的数据类型
document.write(typeof name + "<br>"); //string
document.write(typeof age + "<br>"); // number
document.write(typeof code + "<br>"); // undefined
document.write(typeof isStudent + "<br>"); // boolean
document.writeln("姓名:" + name + "<br>");
document.writeln("性别:" + gender + "<br>");
document.writeln("年龄:" + age + "<br>");
console.log(name);
console.log(gender);
</script>
7、定义变量如果不写var,这个变量是全局变量
<script type="text/javascript">
// 定义变量如果不写var,这个变量是全局变量
a=10;
document.writeln(a);
</script>
第二章
1、输入一个时间,根据时间进行判断
if结构第一种形式
if...else结构
if...else if结构
<script type="text/javascript">
// 输入一个时间,根据时间进行判断
// prompt() : 输入框
var t = prompt("请输入现在是几点:",0);
// if结构第一种形式
if(t!=null){
document.write("点击了确定按钮");
}
// if...else
if (t >= 6 && t <= 18) {
alert("白天好");
} else {
alert("晚上好");
console.log("good night!");
}
// if...else if结构
if (t >= 6 && t <= 11) {
alert("上午好");
} else if (t > 11 && t <= 13) {
alert("中午好");
} else if (t > 13 && t <= 18) {
alert("下午好");
} else {
alert("晚上好");
}
</script>
2、for循环 跳过本次循环后面语句,执行下一次循环
<script type="text/javascript">
for(var i = 0;i <= 10;i++) {
if(i > 5 && i < 8 ) {
continue; // 跳过本次循环后面语句,执行下一次循环
}
document.write(i);
}
</script>
3、输入框中输入的内容是string型
switch进行等值判断,使用的是 === 这个严格等于的判断
<script type="text/javascript">
// 输入框中输入的内容是string型
var number=prompt("请输入0~6之间的数字",0);
// 输出今天是星期几
if (number != null) {
// switch进行等值判断,使用的是 === 这个严格等于的判断
switch(number) {
case "0":document.write("星期天");break;
case "1":document.write("星期一");break;
case "2":document.write("星期二");break;
case "3":document.write("星期三");break;
case "4":document.write("星期四");break;
case "5":document.write("星期五");break;
case "6":document.write("星期六");break;
default:document.write("数字范围错误!");break;
}
switch(number) {
case "1":
case "2":
case "3":
case "4":
case "5":document.write("我要学习!");break;
case "0":
case "6":document.write("我要开黑!");break;
default:document.write("数字范围错误!");break;
}
}
</script>
4、赋值运算符
<script type="text/javascript">
var a = 10,b = 20; // 赋值
// 复合赋值
a += b; // a=30 相当于 a=a+b
a -= 5; // a=25
a *= 3; // a=75
a /= 10; // a=7.5
a %= 5; // a=2.5
document.write("a=" + a);
</script>
5、关系运算符
<script type="text/javascript">
// js是弱类型的编程语言 c#是强类型
var a = 10 , b = 20 , c = "10";
document.write(a == b);
document.write("<br>");
document.write(a != b);
document.write("<br>");
// == 只比较值是否相等
document.write(a == c); // true, 会发生类型转换,把比较数据转成同一种类型
document.write("<br>");
// == 既比较值是否相等,又比较类型是否相同(更加严格的相等的比较)
document.write(a === c); // false,不会发生类型转换
document.write("<br>");
document.write(typeof a); // number
document.write("<br>");
a="tom";
document.write(typeof a); // string
</script>
6、逻辑运算符
<script type="text/javascript"> var a = 10; // 与:&&,多个条件要同时满足,结果才为true document.write(a >= 0 && a <= 100); // true // 或:||,多个条件只要满足一个,结果就为true document.write(a < 0 || a > 100); // false // 非: !, 表示相反,非真即为假,。。。。 document.write(!(a < 0 || a > 100)); // true </script>
7、算术运算符
<script type="text/javascript">
var a = 10 ,b = 20, c = "hello";
var d = a + b; // 加法
var e = a + c; // + 连接
document.write("d=" + d + "<br>");
document.write("e=" + e + "<br>");
var f = a / b;
var g = a / 0; // Infinity 正无穷大 -Infinity 负无穷大
document.write("f=" + f + "<br>");
document.write("g=" + g + "<br>");
var h = a % b; // 求余数:取模运算
document.write("h=" + h + "<br>");
// 自增、自减
a++;
++a;
b--;
--b;
document.write("a=" + a + "<br>"); // a=12
document.write("b=" + b + "<br>");
var x = a++;
document.write("a=" + a + "<br>");
document.write("x=" + x + "<br>");
</script>
8、条件运算符
求两数的最大值
<script type="text/javascript"> var a = 100 , b = 20; // 条件运算符:求两数的最大值 var max = a > b ? a : b; document.write(max); </script>
9、循环运算符
<script type="text/javascript">
/*
循环结构:for、while、do...while、
for...in(后续学习)
*/
var sum = 0;
for(var i = 0;i <= 10;i++) {
document.write(i + "<br>");
sum += i;
}
//document.write("i=" + i);
document.write("和" + sum);
for(var i = 1; i <= 5 ;i++) {
var width= 100 + i * 100;
document.write("<hr width='"+ width+"'>");
}
var i = 0;
while(i <= 10) {
document.write(i);
i++;
}
var i = 0;
do{
document.write(i);
i++;
} while(i <= 10);
// 死循环
var i = 0;
for(;;) {
document.write(i);
i++;
if(i > 10) {
break; // 跳出循环
}
}
var names=["小明","小红","小黑"];
for(var i = 0;i < names.length; i++) {
document.writeln(names[i]);
}
</script>
10、把函数当成参数传递:这种函数叫回调函数
匿名函数做为回调函数
<script type="text/javascript">
function zsSend(){
console.log("发红包5201314!");
}
function lsSend(){
console.log("送花999朵!");
}
function sendGift(f,gf_name){
f(); // 函数调用
console.log("女朋友是:" + gf_name);
}
// 送礼物(把函数当成参数传递:这种函数叫回调函数)
sendGift(zsSend,"小红");
sendGift(lsSend,"小白");
sendGift(function(){
console.log("啥也不送……");
},"小黑"); // 匿名函数做为回调函数
</script>
11、函数的参数
获取传递过来的参数
<script type="text/javascript">
function add(a,b){
console.log(a + b);
}
// 调用:参数的数量可以跟定义不同
add(); // NaN:not a number 非数字
add(1); // NaN
add(1,2); // 3
add(1,2,3); // 3
// arguments 对象:存储所有传递过来的参数
function test1(){
// 获取传递过来的参数:对arguments进行遍历
for(var i = 0;i < arguments.length; i++){
console.log(arguments[i]);
}
}
test1(10,20);
test1(100,200,300,400,500);
function addNumber(a,b){
console.log("---------------------");
//console.log(a);
//console.log(b);
var sum = 0;
if (arguments.length <= 2) {
sum = a + b;
} else{
for(var i = 0;i < arguments.length; i++){
sum += arguments[i];
}
}
return sum;
}
console.log(addNumber(1,2));
console.log(addNumber(1,2,3,4,5));
</script>
12、函数定义
无参无返回
带参函数,无返回
带多个参数,有返回(通过return返回)
通过Function类构造出一个函数表达式
1、 <script type="text/javascript">
// 传统的函数定义写法
// 无参无返回
function showMsg(){
console.log("你好");
}
// 函数调用
showMsg();
// 带参函数,无返回
function showMsg2(name){
console.log("你好," + name);
}
// 函数调用
showMsg2("小明");
showMsg2("小红");
// 带多个参数,有返回(通过return返回)
function addNumber(a,b){
var c = a + b;
return c; // 返回结果
}
// 函数调用
var sum = addNumber(1,2);
console.log(sum);
</script>
2、 <script type="text/javascript">
// 函数表达式(函数型变量)
var showMsg=function (){ // 省去函数名
console.log("你好");
}; // 分号结束
//var a=showMsg;
//a();
// 调用函数
showMsg();
console.log(typeof showMsg);//function
var showMsg2=function(name){
console.log("你好," + name);
};
// 调用函数
showMsg2("小明");
var sum=function(a,b){
return a + b;
};
// 调用函数
var total = sum(10,20);
console.log(total);
// 通过Function类构造出一个函数表达式
var test1 = new Function("console.log('你好');");
test1();
var test2 = new Function("a","b","return a+b;");
console.log(test2(10,20));
console.log(typeof test2); // function
</script>
13、立即执行函数
<script type="text/javascript">
// 立即执行函数
(function (){
console.log("你好");
})();
(function (name){
console.log("你好," + name);
})("小明");
</script>
14、匿名函数
<input type="button" id="btn1" value="OK" onclick="a();" />
<input type="button" id="btn2" value="OK" onclick="b();" />
<input type="button" id="btnOK" value="OK" />
<script type="text/javascript">
// 不是匿名函数
function a(){
alert('OK');
}
var b=function(){ // 匿名函数
alert('OK');
};
// 给按钮绑定点击事件
// document.getElementById("btnOK").onclick=a;// 绑定函数名
document.getElementById("btnOK")
.onclick=function(){ // 匿名函数
alert('hello');
};
</script>
15、文本框输入
isNaN:是否是 非数字,如果是数字,返回false
绑定点击事件
请输入年龄:<input type="text" id="name1" value="" />
<input type="button" id="btn1" value="OK"/>
<script type="text/javascript">
function a(){
// 获取年龄(文本框输入的值默认是string型)
var age=document.getElementById("name1").value;
console.log(typeof age); // string
if(isNaN(age)) { // isNaN:是否是 非数字,如果是数字,返回false
alert("输入错误");
return;
}
if ( parseInt(age) >= 18){
alert("成年");
} else {
alert("未成年");
}
}
// 绑定点击事件
document.getElementById("btn1").onclick=a;
</script>
16、预定义函数
类型转换方法
保留小数位数
针对特定的字符进行编码
<script type="text/javascript"> // 类型转换方法 // string-->number var a = "123.6"; // string型 var b = Number(a); // 转number型 console.log(b + " " + (typeof b)); var c = parseInt(a); // 转成整数 console.log(c + " " + (typeof c)); var d = parseFloat(a); // 转成浮点数 console.log(d + " " + (typeof d)); </script> <script type="text/javascript"> // number--->string var x = 123.12345; var s1 = String(x); // 转string console.log(s1 + " " + (typeof s1)); var s2 = x.toString(); console.log(s2 + " " + (typeof s2)); // 保留小数位数 var s3 = x.toFixed(2); console.log(s3 + " " + (typeof s3)); </script> <script type="text/javascript"> var letter="Need tips? Visit RUNOOB!"; console.log(escape(letter));// 针对特定的字符进行编码 </script>
第三章
1、获取页面元素
通过id获取某个页面元素
<style type="text/css">
#p1{
color: red;
}
</style>
</head>
<body>
<p id="p1" >aaaaaaaaaaaaaaa</p>
<p id="p2">bbbbbbbbbbbbbbb</p>
<script type="text/javascript">
// 通过id获取某个页面元素
function $(id){
return document.getElementById(id);
}
var p1=$("p1");
console.log(p1);
</script>
2、事件基本概念
<input type="button" value="OK" onclick="showInfo();" />
<script type="text/javascript">
// 事件类型:onclick
// 事件发起者:按钮本身
// 事件处理程序:showInfo函数
function showInfo(){
document.write("hello");
}
</script>
3、事件绑定
通过HTML事件属性(on开头)进行事件绑定
dom1级别事件绑定:纯js,事件跟html内容分离
通过id获取某个页面元素
通过id获取某个页面元素
给按钮绑定点击事件(绑定多次,最后一次有效)
直接绑定已经定义好的函数
可以绑定匿名函数
取消事件绑定
(1)通过HTML事件属性(on开头)进行事件绑定
<!--1、通过HTML事件属性(on开头)进行事件绑定-->
<input type="button" value="OK" onclick="showInfo();" />
<script type="text/javascript">
function showInfo(){
document.write("hello");
}
</script>
(2)dom1级别事件绑定:纯js,事件跟html内容分离
通过id获取某个页面元素
通过id获取某个页面元素
给按钮绑定点击事件(绑定多次,最后一次有效)
直接绑定已经定义好的函数
可以绑定匿名函数
取消事件绑定
<input type="button" id="btnOK" value="OK" />
<!--dom1级别事件绑定:纯js,事件跟html内容分离-->
<script type="text/javascript">
// 通过id获取某个页面元素
function $(id){
return document.getElementById(id);
}
// 事件处理程序
function showInfo(){
document.write("hello");
}
function a(str){
console.log(str);
}
function b(){
console.log("b");
}
// 给按钮绑定点击事件(绑定多次,最后一次有效)
// 直接绑定已经定义好的函数
// $("btnOK").onclick=showInfo;
// 可以绑定匿名函数
$("btnOK").onclick=function(){
document.write("hello js");
a("aaaaaaaaaaa");b();
};
// 取消事件绑定
// $("btnOK").onclick=null;
</script>
(3)dom2级别事件绑定
通过id获取某个页面元素
事件处理程序
事件绑定:addEventListener(事件名,事件处理程序,false)
// 事件名,没有on // 多次绑定都有效果
如果要取消事件绑定
<input type="button" id="btnOK" value="OK"/>
<!--dom2级别事件绑定-->
<script type="text/javascript">
// 通过id获取某个页面元素
function $(id){
return document.getElementById(id);
}
// 事件处理程序
function showInfo(){
console.log("hello");
}
// 事件绑定:addEventListener(事件名,事件处理程序,false)
// 事件名,没有on
// 多次绑定都有效果
$("btnOK").addEventListener("click",showInfo,false);
$("btnOK").addEventListener("click",function(){
console.log("hello js");
},false);
// 如果要取消事件绑定
// $("btnOK").removeEventListener("click",showInfo,false);
</script>
4、事件流
通过id获取某个页面元素
false表示事件流模型:使用事件冒泡(从内到外的事件顺
true表示事件流模型:使用事件捕获(从外到内的事件顺序)
<div id="d1">
<p id="p1">aaaaa</p>
</div>
<script type="text/javascript">
// 通过id获取某个页面元素
function $(id){
return document.getElementById(id);
}
// false表示事件流模型:使用事件冒泡(从内到外的事件顺序)
// true表示事件流模型:使用事件捕获(从外到内的事件顺序)
$("d1").addEventListener("click",function(){
console.log("div");
$("d1").style.border="1px solid red";
},false);
$("p1").addEventListener("click",function(){
console.log("p");
$("p1").style.color="red";
},false);
</script>
5、Event事件
事件对象:Event,包含了关于事件的详细信息
获取事件对象
事件类型
鼠标坐标
<script type="text/javascript">
// 事件对象:Event,包含了关于事件的详细信息
window.onmousemove=function(e){
var eve = e || window.event;// 获取事件对象
document.write("事件类型:" + eve.type);
document.write("鼠标坐标:" + eve.clientX + ":" + eve.clientY);
};
</script>
6、onload:加载事件
<title></title>
<script type="text/javascript">
// onload 加载事件
/*window.onload=function(){
alert("hello");
};*/
window.addEventListener("load",function(){
alert("haha");
},false);
</script>
</head>
<!--<body onload="alert('OK')">-->
<body>
</body>
7、onmouseover:当鼠标指针悬停于某元素之上时执行脚本
onmouseout:当鼠标指针移出某元素时执行脚本
通过id获取某个页面元素
修改css效果
元素显示隐藏
<p id="p1">aaaaa</p>
<script type="text/javascript">
// 通过id获取某个页面元素
function $(id){
return document.getElementById(id);
}
$("p1").onmouseover=function(){
// 修改css效果
$("p1").style.color = "#f00";
$("p1").style.backgroundColor = "green";
//$("p1").style.fontSize = "30px";
//$("p1").style.border = "1px solid blue";
// 元素显示隐藏
// $("p1").style.display = "block"; //none隐藏
};
$("p1").onmouseout=function(){
$("p1").style.color = "#000";
$("p1").style.backgroundColor = "#fff";
}
</script>
8、所有script代码都放到一起
加载事件:在页面元素加载完后执行
进行其它的事件绑定
偶数循环
图片更换
js文件
function $(id){
return document.getElementById(id);
}
// 加载事件:在页面元素加载完后执行
window.onload=function(){
document.bgColor = "#ccc";
$("p1").style.fontSize = "30px";
$("p1").style.fontFamily = "隶书";
$("p1").style.backgroundColor = "#0f0";
$("p1").style.color = "#fff";
$("p1").style.border = "5px dashed #0ff";
//$("p1").style.display = "block";
// 进行其它的事件绑定
$("btnOK").onclick = showNumbers;
$("myImg").onmouseover = imgOver;
$("myImg").onmouseout = imgOut;
};
//偶数循环
function showNumbers(){
for(var i = 0;i <= 10;i += 2){
document.write(i);
}
}
//图片更换
function imgOver(){
$("myImg").style.border = "5px solid red";
$("myImg").src = "img/3.jpeg";
}
function imgOut(){
$("myImg").style.border = "5px solid #ccc";
$("myImg").src = "img/2.png";
}
html
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/1.js"></script>
<style type="text/css">
#img1 img{
width: 100px;
height: 150px;
}
#img1 img{
border: 5px solid #CCC;
border-radius: 10px;
}
</style>
</head>
<body>
<p id="p1">你好</p>
<input type="button" id="btnOK" value=" 输出 " />
<div id="img1">
<img src="img/2.png" id="myImg">
</div>
</body>
9、事件对象
(1)
event:事件对象 ,如果要获取跟事件相关的数据,可以从事件对象中获取
获取事件对象
获取事件类型
<input type="button" name="" id="btn1" value="OK" />
<script type="text/javascript">
// 事件对象event:描述了事件的详细信息
// 如果要获取跟事件相关的数据,可以从事件对象中获取
// 比如: 按下按键时,想要知道用户按了哪个按键
// 比如:鼠标移动时,想要知道鼠标的具体位置
document.getElementById("btn1").onclick=function(e){
var eve = e || window.event; // 获取事件对象
document.write(eve.clientX + ":" + eve.clientY);
document.write(eve.screenX + ":" + eve.screenY);
// 获取事件类型
document.write(eve.type); // click
//
};
</script>
(2)想要知道用户点击的是哪个按钮?
获取事件源:srcElement
按钮文本
this关键字:表示当前触发事件的对象
<input type="button" id="btn2" value="2" />
<input type="button" id="btn3" value="3" />
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
function showInfo(e){
// 想要知道用户点击的是哪个按钮?
// 获取事件源:srcElement
var eve = e || window.event;
var mybtn= eve.srcElement;
//alert(mybtn.value); // 按钮文本
// this关键字:表示当前触发事件的对象
alert(this.value);
}
$("btn1").onclick = showInfo;
$("btn2").onclick = showInfo;
$("btn3").onclick = showInfo;
</script>
(3)只能输入数字
获取事件对象
keyCode表示按键
只能输入数字:
<input type="text" id="myTxt" />
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
$("myTxt").onkeypress=function(e){
var eve = e || window.event; // 获取事件对象
// keyCode表示按键
//alert(eve.keyCode)
if(!(eve.keyCode >=48 && eve.keyCode <= 57)){
return false;
}
};
</script>
(4)考虑兼容性 事件对象event
在事件冒泡中,this和currentTarget是一致的。
(target目标对象)
如何阻止事件冒泡:阻止事件流往外继续扩散
w3c的方法是e.stopPropagation(),
IE则是使用e.cancelBubble = true
<title></title>
<style type="text/css">
#d1{
width: 200px;
height: 200px;
border: 1px solid red;
}
#p1{
width: 100px;
height: 100px;
border: 1px solid green;
}
</style>
</head>
<body>
<div id="d1">
<p id="p1">aaaa</p>
</div>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
$("d1").addEventListener("click",function(e){
// 考虑兼容性
var eve = e || window.event; // 事件对象
// 在事件冒泡中,this和currentTarget是一致的。
console.log(this); //div
console.log(eve.currentTarget);//div
console.log(eve.target);//p (target目标对象)
},false);
$("p1").addEventListener("click",function(e){
var eve = e || window.event;
console.log(this); //p
console.log(eve.currentTarget);//p
console.log(eve.target);//p (target目标对象)
// 如何阻止事件冒泡:阻止事件流往外继续扩散
/*
w3c的方法是e.stopPropagation(),
IE则是使用e.cancelBubble = true
*/
if(window.event){
window.event.cancelBubble=true;
}else{
e.stopPropagation();
}
},false);
</script>
第四章
1、节点属性
节点名:DIV
节点值
节点类型:1 表示元素节点
父节点
所有子节点
第一个子节点
最后一个子节点
前一个兄弟节点
后一个兄弟节点
返回属性列表
<div id="d1" class="c1" style="color: red;">
<h1>aaaaaaaa</h1>
</div>
</body>
</html>
<script type="text/javascript">
function $(id){
return document.getElementById(id);
}
var div=$("d1");
console.log(div.nodeName); //节点名:DIV
console.log(div.nodeValue); //节点值:仅针对有文本的节点(文本节点、属性节点、注释节点)
console.log(div.nodeType); //节点类型:1 表示元素节点
console.log(div.parentNode);// 父节点
console.log(div.childNodes); // 所有子节点
for(var i=0;i<div.childNodes.length;i++){
console.log("子节点:"+div.childNodes[i].nodeName)
}
console.log(div.firstChild); // 第一个子节点
console.log(div.lastChild); // 最后一个子节点
console.log(div.previousSibling); // 前一个兄弟节点
console.log(div.nextSibling); // 后一个兄弟节点
console.log(div.attributes); // 返回属性列表
</script>
2、获取节点对象
根据选择器查找单个元素对象
根据选择器查找多个元素对象
缩小查找范围
<style type="text/css">
#d1{
border: 1px solid red;
}
</style>
</head>
<body>
<div id="d1">
<p>aaaaaaaaaaaaa</p>
<p class="c1">bbbbbbbbbbbbbbb</p>
<p>cccccccc</p>
<p class="c1">dddddd</p>
</div>
<h1 class="c1">aaa</h1>
<p class="c1">eeeeee</p>
</body>
</html>
<script type="text/javascript">
// 根据选择器查找单个元素对象
var ele1=document.querySelector("#d1");
console.log(ele1);
// 根据选择器查找多个元素对象
var ele2=document.querySelectorAll("p");
// var ele2=document.querySelectorAll(".c1");
// var ele2=document.querySelectorAll("#d1 .c1");
// var ele2=ele1.querySelectorAll("p.c1"); // 缩小查找范围
console.log(ele2);
</script>
3、获取节点的方法
根据id获取元素对象(document表示文档对象)
通过标签名获取元素对象
innerText表示节点内部的文本
通过name属性来获取元素对象
通过class属性来获取元素对象
<style type="text/css">
.c1{
color: red;
}
</style>
</head>
<body>
<div id="d1">
<p>aaaaaaaaaaaaa</p>
<p class="c1">bbbbbbbbbbbbbbb</p>
<p>cccccccc</p>
<p class="c1">dddddd</p>
<h1 class="c1">aaa</h1>
</div>
<form name="myform" action="#" method="post">
<input type="checkbox" name="hobby" value="吃" />吃
<input type="checkbox" name="hobby" value="玩" />玩
<input type="checkbox" name="hobby" value="乐" />乐
</form>
</body>
</html>
<script type="text/javascript">
// 根据id获取元素对象(document表示文档对象)
var div=document.getElementById("d1");
console.log(div);
// 通过标签名获取元素对象
var all=document.getElementsByTagName("p");
for(var i=0;i<all.length;i++){
console.log("段落:" + all[i].innerText); // innerText表示节点内部的文本
}
// 通过name属性来获取元素对象
var hobbys=document.getElementsByName("hobby");
for(var i=0;i<hobbys.length;i++){
console.log("爱好:" + hobbys[i].value);
}
// 通过class属性来获取元素对象
var eles=document.getElementsByClassName("c1");
for(var i=0;i<eles.length;i++){
console.log("element:" + eles[i].innerText);
}
</script>
4、对元素节点的操作
获取div
针对节点进行一些操作
获取或设置元素的内容
获取或设置元素的css效果
获取或设置元素的属性值
特别注意: 修改class属性
绑定事件
<style type="text/css">
.d1{
background-color: #ccc;
}
.d2{
background-color: aquamarine;
}
</style>
</head>
<body>
<div id="d1" class="d1">
<h1>hello,<span>js</span></h1>
</div>
</body>
</html>
<script type="text/javascript">
// 获取div
var div = document.querySelector("#d1");
// 针对节点进行一些操作
//1 获取或设置元素的内容
var txt = div.innerText; // 内部文本
console.log(txt);
var txt2 = div.innerHTML; // 内部的html结构
console.log(txt2);
div.innerText = "你好";
div.innerHTML = "<h1 style='color:red;'>你好</h1>";
//2 获取或设置元素的css效果
div.style.border = "1px solid red";
div.style.width = "200px";
div.style.display = "block";
//3 获取或设置元素的属性值
//console.log(div.id); // 获取属性值
//div.id = "d2"; // 修改属性值
// 特别注意: 修改class属性
div.className = "d2";
//4 绑定事件
div.onclick = function(){
alert("hello");
};
</script>
5、对元素的操作
<body>
<p>aaaaaaaaa</p>
<p>bbbbbbbbbbb</p>
<p>ccccccccc</p>
</body>
</html>
<script type="text/javascript">
var ps = document.getElementsByTagName("p");
for(var i=0;i<ps.length;i++){
ps[i].onclick=function(){
alert(this.innerHTML);
};
}
</script>
6、复制删除
<title></title>
<script src="js/new_file.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
#messageContent p span{
font-size: 18px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>留言板</h1>
留言内容:<input type="text" id="userMsg" />
<input type="button" id="btnAdd" value="留言" /> <br>
<div id="messageContent" style="border: 1px solid red;">
<p style="display: none;">
<span>N楼:</span>
<span>测试测试</span>
<a href="#">删除</a>
</p>
</div>
<table border="1" cellspacing="0" cellpadding="0">
<tr><th>姓名</th><th>年龄</th><th>操作</th></tr>
<tr>
<td>tom</td>
<td>18</td>
<td><input type="button" value="删除" onclick="a()"/></td>
</tr>
<tr>
<td>tom</td>
<td>18</td>
<td><input type="button" value="删除" onclick="a()"/></td>
</tr>
<tr>
<td>tom</td>
<td>18</td>
<td><input type="button" value="删除" onclick="a()"/></td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
function a(){
var tr=window.event.srcElement.parentNode.parentNode;
tr.parentNode.removeChild(tr);
}
</script>
第五章
1、Array对象
定义数组
指定长度
指定数据
排序,默认升序
反转数组元素(升序后反转得到降序结果)
数组遍历
for...in 遍历,相当于c#的foreach循环
<script type="text/javascript">
// 定义数组
var arr1 = new Array();
var arr2 = new Array(10); // 指定长度
var arr3 = new Array(2,3,4,5); // 指定数据
console.log(arr1.length); // 长度为0
console.log(arr2.length); // 长度为10
console.log(arr3.length); // 长度为4
var arr4 = [];
var arr5 = [,,,,,,,,,,];
var arr6 = [20,34,45,15]
console.log(arr4.length); // 长度为0
console.log(arr5.length); // 长度为10
console.log(arr6.length); // 长度为4
arr6.sort(); // 排序,默认升序
// arr6.reverse(); // 反转数组元素(升序后反转得到降序结果)
// 数组遍历
for(var i=0;i<arr6.length;i++){
console.log("第" + (i +1) + "个:" + arr6[i]);
}
// for...in 遍历,相当于c#的foreach循环
for(var i in arr6){ // 变量i是下标,string型
// console.log(typeof i); // string
console.log("第" + (parseInt(i) + 1) + "个:" + arr6[i]);
}
console.log(arr6);
console.log(arr6.toString());
</script>
2、Math对象
圆周率
绝对值
返回两个数中较大的数
计算2的10次方
开方
三个取整的方法
向上取整
向下取整
四舍五入取整
生成随机数
随机生成数组下标
<script type="text/javascript"> console.log(Math.PI); // 圆周率 console.log(Math.E); console.log(Math.abs(-1000)); // 绝对值 console.log(Math.max(10,30)); // 返回两个数中较大的数 console.log(Math.min(10,30)); // console.log(Math.pow(2,10)); // 计算2的10次方 console.log(Math.sqrt(99)); // 开方 // 重点 // 三个取整的方法 console.log(Math.ceil(1.1)); // 2 向上取整 console.log(Math.floor(1.9)); // 1 向下取整 console.log(Math.round(1.4)); // 1 四舍五入取整 // 生成随机数 console.log(Math.random()); // 0~1之间的随机小数 // 生成随机整数 var x = Math.floor(Math.random() * 10); // 0~9的整数 var y = Math.floor(Math.random() * 10 + 1) ; // 1~10 var z = Math.floor(Math.random() * 21 + 10) ;// 10~30 // 生成m~n之间的随机整数,包含m和n // Math.floor(Math.random() * (n-m+1) + m) ; // 随机生成数组下标 var numbers=[1,31,4345,64,43,3332,45]; var idx = Math.floor(Math.random() * numbers.length); alert(numbers[idx]); </script>
3、String对象
(1)
字面量直接赋值
通过构造函数
访问某一个字符
字符串连接
根据编码值返回指定的字符
<script type="text/javascript">
var s1 = "abc"; // 字面量直接赋值
var s2 = new String("abc"); // 通过构造函数
console.log(typeof s1); // string
console.log(typeof s2); // object
console.log(s1 + " " + s2);
console.log("字符串长度:" + s1.length); // 3
// 访问某一个字符
console.log("第一个字符:" + s1[0]); // a
console.log("最后一个字符:" + s1[s1.length-1]); // c
console.log("第一个字符:" + s1.charAt(0)); // a
console.log("最后一个字符:" + s1.charAt(s1.length-1)); // c
console.log("第一个字符的编码:" + s1.charCodeAt(0)); // 97
console.log("最后一个字符的编码:" + s1.charCodeAt(s1.length-1)); // c
// 字符串连接
var s3 = s1 + "xyz";
var s4 = s1.concat("xyz");
console.log("s3=" + s3);
console.log("s4=" + s4);
// 根据编码值返回指定的字符
var s5 = String.fromCharCode(65);
console.log("s5=" + s5);
</script>
(2)查找:没有找到,返回-1
返回第一次出现位置的下标
返回最后一次出现位置的下标
截取:
两个参数:开始下标和结束下标,但不包含结束下标的字符
默认截取到最后
分割: 得到多个子字符串结果
大小写
输出对象
原始值
<script type="text/javascript">
var email = "123123123123123@qq.com";
// 查找:没有找到,返回-1
var idx1 = email.indexOf("@"); // 返回第一次出现位置的下标
var idx2 = email.lastIndexOf("@");// 返回最后一次出现位置的下标
console.log(idx1 + " " + idx2);
// 截取:
var s1 = email.substring(0,idx1);// 两个参数:开始下标和结束下标,但不包含结束下标的字符
var s2 = email.substring(idx1 + 1); // 默认截取到最后
console.log(s1 + " " + s2);
// 分割: 得到多个子字符串结果
var s3 = email.split("@");
for(var i=0;i<s3.length;i++){
console.log(s3[i]);
}
// 大小写
console.log(email.toUpperCase());// 大写
console.log(email.toLowerCase());// 小写
var aa = new String("xxxxx");
console.log(aa); // 输出对象
console.log(aa.valueOf()); // 原始值
</script>
4、Date对象
(1)
当前系统时间
指定参数
指定毫秒数
指定年月日,月份用0~11表示
指定年月日,月份用0~11表示
指定日期时间字符串
时间相减:得到时间间隔的毫秒数
时间大小比较
<script type="text/javascript">
var nowTime = new Date(); // 当前系统时间
//document.write(typeof nowTime);
document.write(nowTime + "<br>");
//document.write(nowTime.toDateString() + "<br>");
//document.write(nowTime.toGMTString() + "<br>");
//document.write(nowTime.toISOString() + "<br>");
document.write(nowTime.toLocaleDateString() + "<br>");
document.write(nowTime.toLocaleTimeString() + "<br>");
document.write(nowTime.toLocaleString()+ "<br>");
// 指定参数
var time1 = new Date(1234543564354); // 指定毫秒数
document.write(time1 + "<br>");
var time2 = new Date(2000,1,5); // 指定年月日,月份用0~11表示
document.write(time2 + "<br>");
var time3 = new Date(2000,1,5,9,30,35); // 指定年月日,月份用0~11表示
document.write(time3 + "<br>");
var time4 = new Date("2000-1-5"); // 指定日期时间字符串
document.write(time4 + "<br>");
// 时间相减:得到时间间隔的毫秒数
document.write(time3 -time4 );
if(time3 > time4) { // 时间大小比较
//alert("OK");
}
</script>
(2)
set开头用于设置时间的某个部分的值
get 开头的方法
获取年份
获取月份
获取日期
获取星期
<script type="text/javascript">
var now = new Date();
// set开头用于设置时间的某个部分的值
//now.setFullYear(2020);
//now.setMonth(0);
//now.setDate(10);
// get 开头的方法
var year = now.getFullYear(); // 获取年份
var month = now.getMonth() + 1; // 获取月份
var day = now.getDate(); // 获取日期
var h = now.getHours(); // 小时
var m = now.getMinutes(); // 分
var s = now.getSeconds(); // 秒
var ms = now.getMilliseconds(); // 毫秒
//document.write("年份:" + year + "<br>");
//document.write("月份:" + month + "<br>");
//document.write("日期:" + day + "<br>");
var wkIdx = now.getDay(); // 获取星期
var weeks = "日一二三四五六";
var mytime = year + "年" + month + "月" + day + "日 " + h + ":" + m + ":" + s + " 星期" + weeks[wkIdx];
document.write(mytime);
</script>
5、自定义对象
(1)创建构造函数: 名称大写开头
定义实例方法
定义静态方法
使用构造函数来初始化对象信息
调用实例方法
调用静态方法
使用构造函数来初始化对象信息
for...in遍历对象
判断是属性还是方法
<script type="text/javascript">
// 创建构造函数: 名称大写开头
function Student(id,name,age){
this.stuId = id;
this.stuName = name;
this.stuAge = age;
// 定义实例方法
this.study = function(){
console.log("学生在学习……");
};
this.playGame = function(game){
console.log("学生在玩" + game);
};
}
// 定义静态方法
Student.Sleeping = function(){
console.log("全班都在睡觉");
};
// 使用构造函数来初始化对象信息
var zs = new Student(1,"张三",18);
document.write("学号: " + zs["stuId"]);
document.write("学号: " + zs.stuId);
document.write("姓名: " + zs.stuName);
document.write("姓名: " + zs.stuAge);
// 调用实例方法
zs.study();
zs.playGame("CF");
// 调用静态方法
Student.Sleeping();
//console.dir(zs);
// for...in遍历对象
for(var i in zs){ // i是属性名或方法名
//console.log(typeof zs[i]);
// 判断是属性还是方法
if(zs[i] instanceof Function){ //值 instanceof 类型:判断某个值是否是指定类型的实例
continue;
}
console.log(zs[i]); // 输出属性值
}
</script>
(2)以字面量方式直接构造对象
调用实例方法
<script type="text/javascript">
// 以字面量方式直接构造对象
var zs = {
stuId:1,
stuName:"张三",
stuAge:18,
stuTime:new Date(),
study:function(){
console.log("在学习中....");
},
playGame:function(game){
console.log("玩" + game);
}
};
document.write("学号: " + zs.stuId);
document.write("姓名: " + zs.stuName);
document.write("年龄: " + zs.stuAge);
document.write("入学时间: " + zs.stuTime.toLocaleString());
// 调用实例方法
zs.study();
zs.playGame("cs");
</script>
(3)创建构造函数: 名称大写开头
定义实例方法
按照年龄排序:要传入自定义排序函数,作为排序规则
升序,反过来减就是降序
<script type="text/javascript">
// 创建构造函数: 名称大写开头
function Student(id,name,age){
this.stuId = id;
this.stuName = name;
this.stuAge = age;
// 定义实例方法
this.study = function(){
console.log("学生在学习……");
};
this.playGame = function(game){
console.log("学生在玩" + game);
};
}
var stus = [
new Student(1,"张三",10),
new Student(2,"李四",20)];
var stus2 =[
{id:1,name:"张三",age:10},
{id:2,name:"李四",age:20},
{id:3,name:"王五",age:15},
];
// 按照年龄排序:要传入自定义排序函数,作为排序规则
stus2.sort(function(a,b){
return a.age - b.age; // 升序,反过来减就是降序
});
for(var i in stus2){
console.log(stus2[i].id + " " + stus2[i].name + " " + stus2[i].age);
}
</script>

浙公网安备 33010602011771号