目录
3.9、getElementsByName和getElementById
1.JavaScript的导入
-
直接在<script>标签中写js语句。
-
导入外部js文件
<head>
<meta charset="UTF-8">
<title>js</title>
<!--js的写法有两种:
嵌入: 直接写在html的 <head> 中
外部: 项目中创建js文件夹,里面放入xx.js文件
网页<script src="xxx"> 引入外部文件
-->
<script>
console.log('44js')
</script>
<script src="js/my.js"></script>
</head>
2.DOM加载顺序
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--
文档对象: document
write() 向页面输出内容
网页中事件: 让浏览器在某个事件来执行 什么(方法)
onload="" 当页面加载完毕之后,来执行
加载页面所有的标签之后,显示内容之前,这个时间。
alert() 弹出对话框
js执行要早于 页面DOM的加载。
运行顺序: dom从上向下加载
head
body
end
onload
显示页面内容
-->
<script>
console.log('head')
</script>
</head>
<body onload="console.log('onload')">
<script>
console.log('body')
var d = new Date();
var time = d.getHours();
if(time < 10){
document.write('good morning')
}else{
document.write('good day')
}
console.log(document.getElementById('p1'))
</script>
<p id="p1">xx</p>
</body>
</html>
<script>
console.log(document.getElementById('p1'))
console.log('end')
</script>
3.常用语法
const :定义常量
js中 == 会类型转换 ,=== ,!== 不进行转换
3.1.数据转换
<script>
var wid = 'a50px';
//NaN not a number
//parseFloat(wid) 50
wid = parseFloat(wid) + 100 + 'px';
console.log(wid)
/*
parseInt(var)
– parseFloat(var)
– Number(var)
*/
</script>
3.2循环
for(i=0; i<arr.length; i++): 此处for循环i可以不用声明
for(i in arr):从数组中循环遍历出下标i
for(i of arr):从数组中循环遍历出元素值i
arr.forEach((v,i) => {} i是下标 , v是元素
<script>
//定义数组,js中数组长度可变
var arr = [3,4,5,6,7];
var arr2 = new Array();
console.log(arr[1])
arr[arr.length] = 100;
console.log(arr)
for(i=0; i<arr.length; i++){
console.log(arr[i])
}
//i是下标
for(i in arr){
console.log(arr[i])
}
//item 元素
for(item of arr){
console.log(item)
}
//i是下标,v是元素
arr.forEach((v,i) => {
console.log(i + ":" + v)
})
</script>
3.3方法定义
function 函数名(参数){方法体}
var 函数名 = function(参数){方法体}
var myFun2 = () => {}:省略function,参数只有一个可以省略
/*
定义方法 关键字 function
没有返回值类型部分
function 方法名(参数列表){
方法体
如需要返回值,直接写return
}
*/
//定义方法
function f(num,str) {
return num + str
}
//调用方法
var result = f(100,'zyw');
console.log(result)
//定义方法2 myFun方法名
var myFun = function(v){
return v*v;
}
console.log(myFun(5))
//定义方法3 省略function
var myFun2 = () => {
console.log('hello')
}
myFun2();
3.4 eval 、let使用
eval():用来解析字符串用来执行
var 声明的变量往往是越域的(类似全局变量,不受{}控制)
let 声明的变量有严格的作用域
//解析字符串,来执行
var s = 'var a=100'
eval(s)
console.log(a) //100
//let 使用,定义变量,方法
//var 声明的变量往往是越域的
//let 声明的变量有严格的作用域
{
var a = 1;
let b = 2;
}
console.log(a)
console.log(b)
//-------------------------------------
//var 可以声明多次
//let 只能声明1次
var a = 1
var a = 2
let b = 3
//let b = 4
console.log(a)
console.log(b)
//-----------------------------------
//var 会变量提升
//let 不存在提升
console.log(a)
var a = 1;
console.log(b)
let b = 2;
3.5、js定义对象
//js定义对象,[]数组 {}对象
let user = {
name: 'zyw',
age: 22,
show: function(){
console.log(this.name,this.age)
}
}
//访问对象的信息
console.log(user.name,user.age)
user.show()
let userArr = [
user,user,user
]
for(u of userArr){
console.log(u.name,u.age)
}
3.6、使用prototype扩展新方法
function Car(){
this.color = 'red';
this.doors = 4;
this.mpg = 23;
this.showColor = function(){
alert(this.color);
};
}
let c = new Car();
//c.showColor()
//对Car的构造方法扩展新的方法
Car.prototype.myFun = function () {
alert(123)
}
c.myFun()
3.7、with的使用
function Car(){
this.color = 'red';
this.doors = 4;
this.mpg = 23;
this.showColor = function(){
alert(this.color);
};
}
let c = new Car();
with(c){
//该代码块中默认c来调用
console.log(color)
showColor()
}
3.8、location.href的用法
self.location.href="url"; //1.仅在本页面打开url。
window.location.href="url"; //2.当前页面打开URL页面。
this.location.href="url"; //3.用法和self.location.href一直。
location.href="url"; //4.当前页面打开URL页面 。
parent.location.href="url"; //5.在父窗口打开此url窗口。
top.location.href="url";//6.在顶层页面打开url(跳出框架)。
let result = true;
if(result){
//自动跳转到百度
location.href = "https://www.baidu.com";
}
3.9、getElementsByName和getElementById
//按标签的name值来获取对象,返回数组
let arr = document.getElementsByName('t1');
console.log(arr.length)
3.10、常用事件
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#btn{
width: 100px;
height: 30px;
background: dodgerblue;
border-radius: 6px;
/*letter-spacing: 10px;*/
line-height: 30px;
color: white;
text-align: center;
}
#btn:active{
background: cornflowerblue;
}
</style>
</head>
<body>
<!--
失去焦点事件onblur
获取焦点onfocus
单击事件 onclick
键盘抬起释放时触发 onkeyup
this.value 文本框输入的值
值改变 onChange
-->
<input onblur="console.log('onblur')"
onfocus="console.log('onfocus')"
onkeyup="console.log(this.value)"/>
<div id="btn" onclick="console.log('onclick')">按 钮</div>
</body>
3.11.数组操作
concat:返回一个新数组;由两个或更多数组组合而成。
join:返回字符串;由数组中的所有元素连接到一起,元素间的间隔符由参赛指定,省略参数则用逗号分割。
reverse:返回一个新数组;由原来的数组反转而成。
pop:移除数组中的最后一个元素并返回该元素。
push:给数组中增加新元素,并返回数组的新长度。
shift:移除数组中的第一个元素并返回该元素。
slice:返回一个新数组,为原数组中的一段。
var newArray = tmpArray.silce(1,3)
sort:返回一个排序后的新数组
toString:返回将Array中的元素转为由逗号分隔的字符串
3.12、字符串操作
charAt(i):返回指定索引位置处的字符。
charCodeAt(i):返回一个整数,代表指定位置上的字符的Unicode编码
concat(str):连接字符串
indexOf(str):返回String对象内第一次出现字符串的字符位置(注意:从左至右查找,返回整数值)
lastindexOf(str):返回String对象中子字符串最后出现的位置。
replace(str1,str2):返回将str1替换为str2后的字符串。
slice(start,end):返回字符串中起始位置为start,结束位置为end(不包括end)的子字符串。
split(separator,limit):将字符串以separator作为分隔符切割成多个子字符串,并将他们作为一个数组返回;如果有limit参数则返回数组的limit个元素。
substr(start,length):返回一个从指定位置开始的指定长度的字符串
substring(start,end):返回一个指定位置之间的子字符串,不包括end
toLowerCase:返回一个字符串,字符串中的字母被转换为小写字母
toUpperCase:跟上面的相反。返回转换为大写字母的字符串
3.13、下拉列表框中的参数
options:所有的选项组成一个数组,options表示整个选项数组,第一个选项即为options[0],第二个即为options[1],以此类推。
selectIndex:返回被选择的选项的索引号,如果选中第一个返回0.
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function f() {
//数据源
let types = [
{id: 1, name: 'x1'},
{id: 2, name: 'x2'},
{id: 3, name: 'x3'},
]
let se = document.getElementById('se')
//types.forEach 循环这个数组
//types.forEach( 你想干点儿啥 )
//v 每个对象
types.forEach(function(v){
//列表添加选项
//new Option(显示文本 ,值)
//se.options 所有选项的集合
//add 添加一项
se.options.add(new Option(v.name,v.id))
})
}
window.onload = f;
</script>
</head>
<body>
<select id="se" onchange="console.log(this.value)">
<option value="0">请选择</option>
</select>
</body>
3.14、设置时间和日期的方法
setYear():设置年数 getYear():返回年数(小于2000年返回两位) getFullYear():返回年数
setMonth():设置当月号数(月份从0开始) getMonth():返回当月号数(比实际小1)
setDate():设置当日号数
setDay():设置星期几 getDay():返回星期几(0表示星期日)
setHours():设置小时数
setMinutes():设置分钟数
setSeconds():设置秒数
setTime():设置毫秒数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算2025圣诞节距离现在的时间</title>
</head>
<body>
<div id="times"></div>
<div id="times2"></div>
</body>
<script>
let timeId = document.getElementById("times");
let timeId2 = document.getElementById("times2");
function time(){
//计算2025年的圣诞节是星期几,距离今天还有多少天。距离我们现在的时间还有多少毫秒(以yyyy-MM-dd hh:mm:ss格式显示)
//先获取2025年圣诞节的时间对象
/*js中月份默认从0开始,所以需要减一*/
let time1=new Date(2025,11,25,0,0,0);
//再获取当前时间对象,两者相减即毫秒数,再通过毫秒数计算天数
let time2 = new Date();
let time = time1-time2;
let str1 = time2.getFullYear()+'-'+
((time2.getMonth()+1)<10?"0"+(time2.getMonth()+1):(time2.getMonth()+1))+'-'+
(time2.getDate()<10?"0"+time2.getDate():time2.getDate())+' '+
(time2.getHours()<10?"0"+time2.getHours():time2.getHours())+':'+
(time2.getMinutes()<10?"0"+time2.getMinutes():time2.getMinutes())+':'+
(time2.getSeconds()<10?"0"+time2.getSeconds():time2.getSeconds());
let day = time/(24*60*60*1000);
timeId.innerHTML="当前北京时间 "+str1+"<br>"+
"2025年圣诞节为周:"+time1.getDay()+" <br>"+
"2025年圣诞节距离现在时间还有:"+time+" 毫秒<br>" +
"2025年圣诞节距离现在时间还剩:"+day+" 天";
}
setInterval("time()",1);
let datetime = new Date(110254671000);
let str2 = datetime.getFullYear()+'-'+
((datetime.getMonth()+1)<10?"0"+(datetime.getMonth()+1):(datetime.getMonth()+1))+'-'+
(datetime.getDate()<10?"0"+datetime.getDate():datetime.getDate())+' '+
(datetime.getHours()<10?"0"+datetime.getHours():datetime.getHours())+':'+
(datetime.getMinutes()<10?"0"+datetime.getMinutes():datetime.getMinutes())+':'+
(datetime.getSeconds()<10?"0"+datetime.getSeconds():datetime.getSeconds());
timeId2.innerText='110254671000毫秒对应的时间是: '+str2
</script>
</html>
3.15、setInterval和setTimeout函数
setInterval:让函数在一定时间内重新执行,外部调用
clearInterval:清除设置的setInterval函数
setTimeOut(函数名,时间间隔,重复次数):让函数在一定时间内重新执行,递归调用,如果不递归调用则仅执行一次
clearTimeout:清除设置的setTimeout函数
<script>
function show(){
let time = new Date()
let str = time.getHours() + ":" +
time.getMinutes() + ":" +
(time.getSeconds() < 10 ? '0'+time.getSeconds() : time.getSeconds())
$('time').innerText = str
//每秒调1次
setTimeout('show()',1000)
}
//方法没有参数,可以不写()
//window.onload 窗体加载事件
window.onload = show
function $(id) {
return document.getElementById(id)
}
</script>
</head>
<body>
<div id="time"></div>
</body>
3.16、Math对象
全局对象,使用时不需要创建实例
属性:LN10:10的自然对数 PI SQRT1_2(1/2的平方根)
方法:
abs(x):返回x的绝对值
ceil(x):返回大于等于x的最小整数
exp(x):返回e的x次方
floor(x):返回小于等于x的最大整数
round(x):舍入到最近整数,(小于或等于0.5小数舍去)
sqrt(x):返回x的平方根
random():随机数
3.17、正则表达式
<title>简单表单示例</title>
<script>
//2
function check(){
var email = document.getElementById('email')
if(email.value == ''){
alert('请输入Email地址')
return false
}else{
alert('你输入的Email地址有效')
}
}
</script>
</head>
<body>
<h2>表单验证</h2>
<!-- 1.required内容不允许为空
2.正则表达式格式验证
3.min , max 数值和日期类型元素 专用属性
4.step , input元素增,减时间隔 -->
<form name="form1" method="post">
<input name="t1" required pattern="^\w.*$" placeholder="字符开头"/>
<br />
<input name="part" pattern="[0-9][A-Z]{3}" placeholder="一个数字三个字母" />
<br />
<input type="submit" />
</form>
<hr />
<!-- 2 -->
<form onsubmit="return check()">
<label for="email">Email</label>
<input name="email" id="email" type="email" /><br />
<input type="submit" />
</form>
</body>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function validate(){
//if(!/^\w{6}$/.test($('t1').value)){
if($('t1').length > 6){
console.log('用户名错误')
return false;
}
if(!/^\w{6}$/.test($('p1').value)){
console.log('密码错误')
return false;
}
//..........
return true;
}
function $(id){
return document.getElementById(id);
}
</script>
</head>
<body>
<!--如果validate()返回false 表单不提交-->
<form action="/add" onsubmit="return validate()">
<input id="t1"/><br/>
<input type="password" id="p1"/>
<input type="submit"/>
</form>
</body>
</html>