-
JS的作用:
-
- 修饰 HTML 标签(CSS)
- 设置 HTML 标签的动作(JS)
- JS特点:基于对象的编程语言,通过浏览器解释执行
- 作用:表单验证、改变标签样式、获取和设置标签属性值
1 表单验证:
<form action="遍历数组的三种方式.html" οnsubmit="return checkAll()" >
<input type = "submit" value="判断"/>
</form>
<form action="遍历数组的三种方式.html" method = "get" id = "myForm">
<input type = "button" value="普通按钮" οnclick="checkForm()"/>
</form>
function checkAll(){
return checkName()&&checkPassWord()&&checkCell()&&checkMail()
}function checkForm(){
if (checkName()&&checkPassWord()&&checkCell()&&checkMail()){
document.getElementById("myForm").submit();
}
}表单拦截
表单中有"提交"按钮的情况:
1 表单提交触发 表单的提交事件 onsubmit
如果返回为false,则不提交表单,否则提交表单
实现步骤:
1 给各个表单元素的验证方法设置返回值
如果验证通过返回true,否则返回false
2 编写一个与onsubmit事件相关函数
调用每个验证方法,如果都返回为true,
则return true,否则return false
3 在form标签中,写onsubmit事件
<form οnsubmit="return 相关函数名()"<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title><style>input{width:300px;height:20px;margin:10px;line-height:20px;text-align:center;}</style></head><body><input type="text" id = "userName" onblur = "checkName()"/><span id="tips" >用户名正确性</span><script src="js/验证表单用户名.js"></script><script src ="js/验证密码.js"></script><script src ="js/验证手机号.js"></script><script src ="js/验证邮箱.js"></script></body> </html>
function checkName(){let userName = document.getElementById("userName").valuelet tipObj =document.getElementById("tips")// let tip = document.getElementById("tips").innerHTML// console.log(tip)if(userName == ""){document.getElementById("tips").innerHTML= "用户名不能为空!"tipObj.style.color = "red"return false;}if(userName.charAt(0)>0 && userName.charAt(0)<9 ){tipObj.innerHTML = "用户名不能以数字开头"tipObj.style.color = "red"return false;}for (let s of userName.toLowerCase()) {if(!(s>="a"&&s<="z") && !(s>=0&&s<=9) && !(s="_")){tipObj.innerHTML = "用户名只能包含字母,数字,下划线"tipObj.style.color = "red"return false;}}if(!(userName.length>=8 && userName.length<=15)){tipObj.innerHTML = "用户名长度为8到15位"tipObj.style.color = "red"return false;}tipObj.innerHTML = "✔"tipObj.style.color = "green"return true;}
function checkPassWord(){let password = document.getElementById("password").valuelet passwordInput = document.getElementById("passwordInput");if(password == ""){passwordInput.innerHTML = "密码不能为空";passwordInput.style.color = "red"return false;}if(!password.length>=8 && password.length <= 15 ){passwordInput.innerHTML = "密码长度为8-15位"passwordInput.style.color = "red"return false;}for (let s of password.toLowerCase()) {if(!(s >= 0 && s<= 9 ) && !(s>="a" && s<="z" ) ){passwordInput.innerHTML = "密码包含字母和数字"passwordInput.style.color = "red";return false;}}passwordInput.innerHTML = "✔";passwordInput.style.color = "green";return true; }
function checkCell(){let cell = document.getElementById("cell").value;let cellInput = document.getElementById("cellInput");if(cell == ""){cellInput.innerHTML= "手机号不能为空"cellInput.style.color = "red";return false;}let m = cell.charAt(0)if(m !== "1"){cellInput.innerHTML= "必须以1开头"cellInput.style.color = "red";return false;}if( cell.charAt(1) !== 3 || cell.charAt(1) !== 8 || cell.charAt(1) !== 5 || cell.charAt(1) !== 7 ){cellInput.innerHTML = "第二位必须3,5,7,8"cellInput.style.color = "red"return false;}if(cell.length != 11){cellInput.innerHTML ="长度为11位"cellInput.style.color = "red"return false;}cellInput.innerHTML = "✔";cellInput.style.color = "green";return true;}
function checkMail(){let mail = document.getElementById("mail").valuelet mailInput = document.getElementById("mailInput");let count = 0;let countdian = 0;if(mail == ""){mailInput.innerHTML = "邮箱不能为空"mailInput.style.color = "red"return false;}for (let s of mail) {if(s == "@"){count++;}if(s == "."){countdian++;}}if(count == 0){mailInput.innerHTML = "邮箱必须包含@"mailInput.style.color = "red"return false;}if(countdian !== 1){mailInput.innerHTML = "邮箱必须包含."mailInput.style.color = "red"return false;}if(mail.indexOf(".")<=mail.indexOf("@")){mailInput.innerHTML = "邮箱的.在@之后"mailInput.style.color = "red"return false;}mailInput.innerHTML = "✔"mailInput.style.color = "green"return true;}
2获取和设置标签属性值:
<input type = "text" id = "mail" onblur = "checkMail()" > <span id = "mailInput" >邮箱必须包含@且仅包含一个.同时@后面包含一个</span> <br>
function checkMail(){let mail = document.getElementById("mail").valuelet mailInput = document.getElementById("mailInput");if(mail == ""){mailInput.innerHTML = "邮箱不能为空"mailInput.style.color = "red"return false;}
一 获取标签对象,属性,值
一) 获取标签对象的方法
1 通过ID获取单个对象
document.getElementById("id名");
2 通过标签名获取一组标签对象
getElementsByTagName("标签名")
二 ) 获取和设置标签的属性值
获取属性值: let 变量名= 标签对象.属性名
赋值: 标签对象.属性名 = 值
注意 :checked,selected,readonly,disabled返回的值为true或false
三) 获取和设置表单元素的值
取值: let 变量名= 表单元素对象.value
赋值: 表单元素对象.value = 值
注意: 获取到的表单元素值,为string类型,如果无值,则为""
四) 修改标签的样式
1) 使用style属性
标签对象.style.样式属性名=值;
innerHTML、innerText 与 textContent 的区别?
innerText 属性返回:
只返回元素及其所有子元素的文本内容,没有 CSS 隐藏文本间距和标签,除了 <script> 和 <style> 元素。
innerHTML 属性返回:
元素的文本内容,包括所有空白和内部 HTML 标签。
textContent 属性返回:
元素和所有后代的文本内容,带有空白和 CSS 隐藏文本,但没有标签。
3改变标签样式
<script>
let index = -1;
function scrollingDisplay(){
if(arguments.length !== 0){
index = arguments[0]
}else{
if(index == 5){
index =-1;
}
index ++;
}
let imgs = document.getElementById("scroll_img").getElementsByTagName("li");
let nums = document.getElementById("scroll_number").getElementsByTagName("li");
for (i = 0; i < imgs.length; i++) {
if(i == index){
imgs[i].style.display = "block"
nums[i].className= "sroll_number_over"
}else{
imgs[i].style.display = "none"
nums[i].className= "";
}
}
}<script>
<div class="scroll_mid">
<ul id="scroll_img">
<li><img src="images/dd_scroll_1.jpg"/></li>
<li><img src="images/dd_scroll_2.jpg"/></li>
<li><img src="images/dd_scroll_3.jpg"/></li>
<li><img src="images/dd_scroll_4.jpg"/></li>
<li><img src="images/dd_scroll_5.jpg"/></li>
<li><img src="images/dd_scroll_6.jpg"/></li>
</ul>
<ul id="scroll_number">
<li class="scroll_number_over" οnmοuseοver="numOver(0)" οnmοuseοut="numOut()">1</li>
<li οnmοuseοver="numOver(1)" οnmοuseοut="numOut()">2</li>
<li οnmοuseοver="numOver(2)" οnmοuseοut="numOut()">3</li>
<li οnmοuseοver="numOver(3)" οnmοuseοut="numOut()">4</li>
<li οnmοuseοver="numOver(4)" οnmοuseοut="numOut()">5</li>
<li οnmοuseοver="numOver(5)" οnmοuseοut="numOut()">6</li>
</ul>
</div>
-
JS如何写在HTML页面中:
- 直接写在标签中的属性中
- 内嵌在页面中的
<script>
标签中 - 定义独立的 JS 文件,在页面最后引入
-
JS的基本语法:
- 定义变量:使用
let
关键字 - 数据类型:undefined, boolean, number, string, object
undefined - 未赋值的变量
boolean - true或false
number - 整数或小数
string - 使用单引号或双引号引起来的一串字符
object - 内置对象,或标签对象 - 定义变量:使用
-
- 运算符:赋值运算符、算术运算符、比较运算符、逻辑运算符
-
分支结构:
0. 判断条件的真假值:
数字:0 表示false ,非0true
字符串: ""为false ,非空串:true
null :false
undefined :false-
if 语句
<body>
<input type = "button" οnclick="display()" value="显示1-100所有偶数,每行10个">
<script>
function display(){
let count = 1;
for(var num = 1; num<=100; num++){
if(num%2 == 0){
document.write(num+" ");
count ++;
if(count ===10){
document.write("<br>")
count = 1;
}
}
}
}</script>
</body> -
if-else 语句
-
if-else-if 语句
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title><style>input{width:300px;height:20px;margin:10px;line-height:20px;text-align:center;}</style></head><body><h1>输入1-99之间的整数,猜数游戏</h1><hr><span>输入第一个数:</span><input type = "text" id = "one"><br><input type = "button" onclick="gess()" id = "two" value="猜一猜"><br><span>结果:</span><input type = "text" id = "result" readonly><script>let random ="" ;let count = 0;function gess(){if( random == ""){random = parseInt(Math.random()*99+1);}console.log(random);let str = document.getElementById("one").value;let num = parseInt(str);if(num > random){document.getElementById("result").value = "大了"}else if(num < random){document.getElementById("result").value = "小了"}else {alert("猜对了!")return;location.reload();}count++;if(count==7){return;location.reload();}}</script></body> </html>
-
switch 语句 (使用 ===判断)
-
-
循环语句:
- while 循环
- for 循环
3) 数组的遍历
3.1) 通过下标使用for循环遍历
for(let i = 0; i<arr.length; i++){
//访问元素 arr[下标]
}
3.2) 使用for -in的方式遍历数组,仅遍历有值的元素
:t 临时变量存储为有值元素的下标
for(let t in arr){
//访问元素 arr[t]
}
2.3) for-of
:t 表示数组元素的值
for(let t of arr){
//数组元素 : t
}
2.4) forEach方法 -
函数:
- 定义语法
- 参数对象
arguments
- 全局函数:parseInt(), parseFloat(), isNaN()
parseInt(),parseFloat():
<input type = "button" onclick="displayAll()" value="显示100-1000的所有水仙花数"><script>function displayAll(){for(var m = 100; m<=999;m++){if(judgeNum(m) == m){alert(m);}}}function judgeNum(num){let hundersPlace = Math.floor(num/100);let onesPlace = Math.floor(num%10);let tensPlace = Math.floor(num%100/10);if((onesPlace*onesPlace*onesPlace + tensPlace*tensPlace*tensPlace+hundersPlace* hundersPlace* hundersPlace) == num){return num;}else{return 0;}}</script>
isNaN() :判断是否为非数值
当值中包含非数值的字符 :true
纯数值 :false 25.6
eval(String):eval() 函数计算或执行参数。
如果参数是表达式,则 eval() 计算表达式
例如: eval("2+3") -->5网页版计算器
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title><style>h1{text-align:center;}div{width :40%;height: 40%;margin: 0 auto;border:10px solid #ffff7f;padding-left: 10px;text-align:center;}input{width:300px;height:20px;margin:10px;line-height:20px;text-align:center;}input:not(:nth-of-type(1),:nth-of-type(2),:nth-of-type(7)){width:85px;height:20px;background-color:#e0e0e0;border:1px solid ;}</style></head><body><div ><h1>简单计算器</h1><hr><span>输入第一个数:</span><input type = "text" id = "one"><br><span>输入第二个数:</span><input type = "text" id = "two"><br><input type = "button" onclick="add()" id = "add" readonly value="+"><input type = "button" onclick="reduce()" id = "reduce" readonly value="-"><input type = "button" onclick="multication()" id = "multication" readonly value="*"><input type = "button" onclick="division()" id = "division" readonly value="/"><br><span>计算结果 : </span><input type = "text" id = "result" readonly></div><script>// document.write(" 计算器 ")// document.write(" <hr> ")// document.write("<br/> ")function add(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alert("值非法")return;}let a = parseFloat(document.getElementById("one").value) let b = parseFloat(document.getElementById("two").value)document.getElementById("result").value = +a +b}function reduce(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alter("值非法")return;}let a = parseInt(document.getElementById("one").value)let b = parseInt(document.getElementById("two").value)document.getElementById("result").value = +a -b}function multication(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alter("值非法")return;}let a = parseInt(document.getElementById("one").value)let b = parseInt(document.getElementById("two").value)document.getElementById("result").value =(+a *b) }function division(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alter("值非法")return;}let a = parseInt(document.getElementById("one").value)let b = parseInt(document.getElementById("two").value)document.getElementById("result").value = (+a /b)}</script></body> </html>
内置对象
1 Math对象
Math.random() : 0~1的随机数
Math.ceil()
Math.floor()
2 Number对象
toFixed(x); :设置数值保留x位小数位,x可省略不保留小数
3 Date对象let date = new Date();
let year = date.getFullYear();
let month = 1 + date.getMonth();
let dateMonth = date.getDate();
let week = date.getDay;
document.write(year+","+month+","+dateMonth+","+week)
1) 创建日期对象
new Date() :返回系统当前日期
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds) // 设置距离1970-01-01的毫秒值
new Date(date string)2) 常用方法
getXXX() :取值,返回数值
setXXX()
3) 示例: 时钟效果
3.1) 在html页面中编写段落标签
<p></p>
3.2) 定义函数,获取日期和时间
使用"innerHTML"把时间赋值给段落标签
3.3) 使用窗体加载事件,调用日期函数
window.onload : 在页面加载时,发生此事件。
3.4) 设置定时器,间隔时长为1秒
//以指定的时间间隔(以毫秒为单位)调用函数
window.setInterval("函数名()",间隔时长);动态显示时间年月日时分秒
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title></head><body><p id = "time"></p><script>function showTime(){let dt = new Date();let year = dt.getFullYear();let month = dt.getMonth()+1;let date = dt.getDate();let week = dt.getDay();let hour = dt.getHours();let minute = dt.getMinutes();let second = dt.getSeconds();document.getElementById("time").innerHTML = year + "年" +month + "月" +date + "日" +week + "星期" +hour + "小时" +jialing(minute) + "分钟" +jialing(second )+ "秒";}window.onload = showTime();window.setInterval("showTime()",1000);function jialing(num){if(num < 10){num = "0" + num;}return num;}</script></body> </html>
4 Array对象1)创建数组对象
var array-name = [item1, item2, ...];
var cars = new Array("Saab", "Volvo", "BMW");
var arr = new Array(5);
2) 常用属性,方法
属性: length
方法:
2.1) arrayObject.splice(index,howmany,item1,.....,itemX)
方法向/从数组中添加/删除项目,然后返回被删除的项目。
参数 描述
index 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany 必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1, ..., itemX 可选。向数组添加的新项目。
2.2) sort()排序的方法
sort() 方法将按字母和升序将值作为字符串进行排序。
如果按数字排,则在sort()中指定排序规则的函数
升序:sort(function(a,b){return a-b})
降序: sort(function(a,b){return b-a})
3) 数组的遍历
3.1) 通过下标使用for循环遍历
for(let i = 0; i<arr.length; i++){
//访问元素 arr[下标]
}
3.2) 使用for -in的方式遍历数组,仅遍历有值的元素
:t 临时变量存储为有值元素的下标
for(let t in arr){
//访问元素 arr[t]
}
3.3) for-of
:t 表示数组元素的值
for(let t of arr){
//数组元素 : t
}
3.4) forEach方法
4) 数组示例: --> 图片轮播<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title></head><body><select name="attacker" id="attacker" onchange="addRole()"><option value="">选择职业</option></select><select name="role" id="role"><option value="">选择角色</option></select><script>let attackers = new Array();attackers["近卫"] = ["史尔特尔","银灰","玛恩纳"];attackers["重装"] = ["星熊","古米"];attackers["术士"] = ["阿米娅","远山"];function addAttacker(){let attacker = document.getElementById("attacker");for (let s in attackers) {let op = new Option(s,s)attacker.add(op,null)}}window.onload = addAttackerfunction addRole(){let attacker = document.getElementById("attacker").value;let role = document.getElementById("role");role.options.length = 1for (let s of attackers[attacker]) {let op = new Option(s,s)role.add(op,null);}}</script></body> </html>
let op =new Option(s,s)
前一个s为给用户看到的页面显示值,
后一个s为页面对应option标签的value值
role.add(op,null)
前者为select标签内增加的option对象,后者对应具体位置
5 String对象
6 RegExp 对象
使用正则表达式实现表单拦截<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title></head><body><form action="index.html" method = "get" id = "myForm"></form><input type = "text" id = "userName" onblur="checkName()"> <span id = "tips" >用户名包含8-15位字母数字下划线不能以数字开头</span> <br><input type = "password" id = "password" onblur="checkPassWord()" > <span id = "passwordInput" >密码包含8-15位字母数字</span> <br><input type="password" id = "repeatPassword" onblur = "checkRepeatPassWord())" ><span id = "repeatPasswordInput" >密码包含8-15位字母数字</span> <br><input type = "text" id = "cell" onblur = "checkCell()" > <span id = "cellInput" >手机号为11位数字,必须以1开头,第二位3,5,7,8</span> <br><input type = "text" id = "mail" onblur = "checkMail()" > <span id = "mailInput" >邮箱必须包含@且仅包含一个.同时@后面包含一个</span> <br><input type = "text" id = "idCar" onblur = "checkIdCar()" ><span id = "idInput" >长度18位,前17位为数字,18位为数字或字母x</span> <br><!-- <input type="text" id = "sex" onblur = "checkSex()" readonly><span id = "" ></span> <br><input type="text" id = "birthday" onblur = "checkBirthday()" readonly><span id = "" ></span> <br> --><!-- <input type = "submit" value="判断"/> --><input type = "reset" value="重置"/><input type = "button" value="普通按钮" onclick="checkAll()"/></form><script src="js/用户正则表达式.js"></script></body> </html>
function checkName(){let userName = document.getElementById("userName").value;let tips = document.getElementById("tips");if(userName == ""){tips.innerHTML = "用户名为空"tips.style.color = "red"return false;}let reg = /^\d/if(reg.test(userName)){tips.innerHTML = "开头不能是数字"tips.style.color = "red"return false;}reg = /[\d \w _]{8,15}/if(!reg.test(userName)){tips.innerHTML = "包含8-15位字母数字下划线 "tips.style.color = "red"return false;}tips.innerHTML ="✔"tips.style.color = "green"return false;}function checkPassWord(){let password = document.getElementById("password").value;let tips = document.getElementById("passwordInput");if(password == ""){tips.innerHTML = "用户名为空"tips.style.color = "red"return false;}reg = /[\d \w _]{8,15}/if(!reg.test(password)){tips.innerHTML = "包含8-15位字母数字下划线 "tips.style.color = "red"return false;}tips.innerHTML ="✔"tips.style.color = "green"return false; }function checkRepeatPassWord(){}function checkCell(){let cell = document.getElementById("cell").value;let tips = document.getElementById("tips");if(cell == ""){tips.innerHTML = "用户名为空"tips.style.color = "red"return false;}let reg = /^1[3578][0-9]{97}/if(!reg.test(cell)){tips.innerHTML = ""tips.style.color = "red"return false;}}function checkMail(){}function checkIdCar(){}
实现一个简单计算器
<!DOCTYPE html> <html><head><meta charset="utf-8"><title></title><style>h1{text-align:center;}div{width :40%;height: 40%;margin: 0 auto;border:10px solid #ffff7f;padding-left: 10px;text-align:center;}input{width:300px;height:20px;margin:10px;line-height:20px;text-align:center;}input:not(:nth-of-type(1),:nth-of-type(2),:nth-of-type(7)){width:85px;height:20px;background-color:#e0e0e0;border:1px solid ;}</style></head><body><div ><h1>简单计算器</h1><hr><span>输入第一个数:</span><input type = "text" id = "one"><br><span>输入第二个数:</span><input type = "text" id = "two"><br><input type = "button" onclick="add()" id = "add" readonly value="+"><input type = "button" onclick="reduce()" id = "reduce" readonly value="-"><input type = "button" onclick="multication()" id = "multication" readonly value="*"><input type = "button" onclick="division()" id = "division" readonly value="/"><br><span>计算结果 : </span><input type = "text" id = "result" readonly></div><script>// document.write(" 计算器 ")// document.write(" <hr> ")// document.write("<br/> ")function add(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alert("值非法")return;}let a = parseFloat(document.getElementById("one").value) let b = parseFloat(document.getElementById("two").value)document.getElementById("result").value = +a +b}function reduce(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alter("值非法")return;}let a = parseInt(document.getElementById("one").value)let b = parseInt(document.getElementById("two").value)document.getElementById("result").value = +a -b}function multication(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alter("值非法")return;}let a = parseInt(document.getElementById("one").value)let b = parseInt(document.getElementById("two").value)document.getElementById("result").value =(+a *b) }function division(){m = document.getElementById("one").valuen = document.getElementById("two").valueif(m == "" || n == ""){alert("值为空")return;}if(isNaN(m)||isNaN(n)){alter("值非法")return;}let a = parseInt(document.getElementById("one").value)let b = parseInt(document.getElementById("two").value)document.getElementById("result").value = (+a /b)}</script></body> </html>