目錄
1 概述
2 HTML嵌入JS代碼三種方式
2.1 第一種方式
2.2 第二種方式
2.3 第三種方式
3 變量
4 數(shù)據(jù)類型
4.1 概述
4.2 Number數(shù)據(jù)類型?
4.3 幾個(gè)值得注意的函數(shù)
4.4 Boolean數(shù)據(jù)類型?
4.5 String數(shù)據(jù)類型
4.6 關(guān)于Object類型
4.7 NaN、undefined、null的區(qū)別
4 函數(shù)
5 事件
5.1 JS中有哪些常用的事件
5.2 重點(diǎn)說說onload事件
5.3 捕捉回車鍵
6 DOM編程
6.1 根據(jù)id獲取元素?
6.2 獲取文本框value
6.3 innerHTML、innerText
7 正則表達(dá)式
8 表單驗(yàn)證
9 復(fù)選框全選與取消全選
10 周期函數(shù)
11 BOM相關(guān)
12 JSON
1 概述
JavaScript是一種腳本語言,縮寫為JS
HTML、CSS、JS他們的關(guān)系?
HTML是主體。
CSS是用來修飾HIML的。
JS是用來操作HTML和CSS的,修改HTML中的元素,修改CSS樣式,達(dá)到網(wǎng)頁的動(dòng)態(tài)效果。
JavaScript包含三大塊:
- ECMAScript:JS的核心語法(ES規(guī)范/ECMA-262標(biāo)準(zhǔn))
- DOM:Document Object Model(文檔對象模型:對網(wǎng)頁當(dāng)中的節(jié)點(diǎn)進(jìn)行增刪該的過程。)HTML文檔被當(dāng)做一顆DOM樹來看待,var domObj = document.getElementById("id");
- BOM:瀏覽器對象模型,關(guān)閉瀏覽器窗口、打開一個(gè)新的窗口、后退、前進(jìn)、瀏覽器地址欄上的地址等,都是BOM編程。
DOM和BOM的區(qū)別和聯(lián)系:BOM的頂級對象是:window;DOM的頂級對象是:document。實(shí)際上BOM是包含DOM的。
2 HTML嵌入JS代碼三種方式
2.1 第一種方式
javascript是一種基于事件驅(qū)動(dòng)型的編程語言,一 般都是依靠事件來觸發(fā)JS代碼執(zhí)行的。
例如:鼠標(biāo)單擊事件click。鼠標(biāo)雙擊事件: dblclick。獲取焦點(diǎn)事件: focus。失去焦點(diǎn)事件: blur
在JS當(dāng)中任何一個(gè)事件都有對應(yīng)的一個(gè)事件句柄。所有的事件句柄都是在事件名稱前面添加on,例如:
click對應(yīng)的事件句柄onclick
dblclick對應(yīng)的事件句柄ondblclick
focus對應(yīng)的事件句柄是: onfocus
blur對應(yīng)的事件句柄是: onblur
注意:所有的事件句柄都是以“標(biāo)簽的屬性”形式存在。
onclick后面的js代碼什么時(shí)候執(zhí)行呢?
不會在頁面打開的時(shí)候執(zhí)行,只有當(dāng)鼠標(biāo)單擊click事件發(fā)生之后才會執(zhí)行這個(gè)JS代碼。
在JS中有一個(gè)內(nèi)置的隱含對象:window,全部小寫。window代表的是瀏覽器窗口對象??梢灾苯幽脕硎褂?。window對象有一個(gè)alert方法/函數(shù),他可以完成彈窗操作。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="button" value="hello" onclick="window.alert(123456)"/>
<!-- 字符串需要用引號 外面雙引號里面單引號,外面單引號,里面雙引號-->
<input type="button" value="hello" onclick="window.alert('hello world')"/>
<!-- window可以省略 -->
<input type="button" value="hello" onclick="alert('hello world')"/>
<!-- 可以一次寫多個(gè)alert,當(dāng)點(diǎn)擊時(shí)會依次顯示出來 -->
<input type="button" value="hello" onclick="window.alert('hello world')
alert('hello jack')
alert('hello lucy')"/>
</body>
</html>
2.2 第二種方式
腳本塊,沒有位置限制,沒有個(gè)數(shù)限制。
在script標(biāo)簽內(nèi)部的代碼會遵循自上而下的順序依次逐行執(zhí)行,并且在script標(biāo)簽內(nèi)部的JS代碼會在頁面打開的時(shí)候執(zhí)行,并不需要事件的發(fā)生.
<!DOCTYPE html>
<script type="text/javascript">
alert("start");
</script>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
alert("hello");
alert("hello2");
alert("hello3");
</script>
</body>
</html>
<script type="text/javascript">
alert("end!");
</script>
2.3 第三種方式
獨(dú)立創(chuàng)建一個(gè)js文件然后引入到html文件中
js文件:
alert("hello")
alert("hello1")
alert("hello2")
html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="js/my.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
3 變量
JS定義變量使用var定義,變量可以賦任何值。
變量沒有賦值的時(shí)候默認(rèn)值是undefined,undefined是JS中的一個(gè)具體存在的值.
以下的這行代碼表示將數(shù)據(jù)輸出到控制臺.上. (控制臺怎么調(diào)出來? F12)
?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var age;
//以下的這行代碼表示將數(shù)據(jù)輸出到控制臺.上. (控制臺怎么調(diào)出來? F12)
console.log(age);
age = true;
console.log(age);
age = "嗨嗨嗨";
console.log(age);
age = 3.14;
console.log(age);
</script>
</body>
</html>
全局變量和局部變量
這個(gè)學(xué)過java也很好理解,在函數(shù)定義一個(gè)變量那自然就是局部變量,在函數(shù)之外自然就是全局變量。但是JS有個(gè)詭異的語法,因?yàn)槎x變量不一定需要用var定義,直接這樣username = "zahngsan";就可以,當(dāng)我們在函數(shù)中這樣定義的時(shí)候,這時(shí)變量就是全局變量了。
4 數(shù)據(jù)類型
4.1 概述
雖然JS中的變量聲明不需要指定數(shù)據(jù)類型,但是在賦值,每一個(gè)數(shù)據(jù)還是有類型的。JS中包含哪些數(shù)據(jù)類型?
- 原始類型:Undefined、Number、String、Boolean、Null
- 引用類型:Object以及Object的子類
- 在ES6之前是這六種,在ES6以及之后還有一個(gè)Symbol類型,一共七種
問題來了,JS中是不區(qū)分?jǐn)?shù)據(jù)類型的,按理說我們往一個(gè)函數(shù)傳任何值都可以,但是當(dāng)我們就想往函數(shù)中傳入的是數(shù)字該怎么辦?
JS中有一個(gè)運(yùn)算符叫做typeof,這個(gè)運(yùn)算符可以在程序的運(yùn)行階段動(dòng)態(tài)的獲取變量的數(shù)據(jù)類型,typeof的語法格式:typeof 變量名
typeof運(yùn)算符的運(yùn)算結(jié)果是以下6個(gè)字符串之一(全部小寫):"undefined"、"number"、"string"、"boolean"、"object"、"function"
如下就可以做到指定別人傳什么內(nèi)容:
<script type="text/javascript">
function sum (a,b){
if(typeof a == "number" && typeof b == "number"){
return a+b;
}
alert(a + "和" + b + "必須都是數(shù)字")
}
alert(sum(10,20))
</script>
4.2 Number數(shù)據(jù)類型?
當(dāng)兩個(gè)變量進(jìn)行運(yùn)算,結(jié)果不是數(shù)字的時(shí)候結(jié)果為NaN;數(shù)字和字符串相加還是字符串,這和java一樣;除數(shù)為0結(jié)果為Infinity;除不盡會保留好多位小數(shù),合理。
<script type="text/javascript">
var a = "擬好";
var b = 12;
alert(a/b)
alert(a+b)
alert(10/0)
alert(10/3)
</script>
4.3 幾個(gè)值得注意的函數(shù)
isNaN函數(shù)
它的意思是,如果不是數(shù)字則返回true(狗吧設(shè)計(jì),繞死人),使用它也可以進(jìn)行數(shù)字限制如下:
function sum(a,b){
if(isNaN(a) || isNaN(b)){
//運(yùn)行到這a或b一定有不是數(shù)字的,因?yàn)椴皇菙?shù)字是true,
//只有都是數(shù)字為false才不會運(yùn)行到這
alert("必須都是數(shù)字")
return;
}
return a+b
}
alert(sum(1,"nih"))
parseInt函數(shù):轉(zhuǎn)為int類型(向下取整)????????parseFloat函數(shù):轉(zhuǎn)為浮點(diǎn)數(shù)????????Math.ceil函數(shù):向上取整
alert(parseInt(3.14))
alert(parseInt("3.999"))
alert(parseFloat("3.24"))
alert(Math.ceil(3.14))
4.4 Boolean數(shù)據(jù)類型?
它可以將內(nèi)容轉(zhuǎn)為boolean也就是true或者false,那么什么內(nèi)容轉(zhuǎn)為true什么內(nèi)容轉(zhuǎn)為false呢?一般是有就為true,沒有就為false,如下:注意,當(dāng)使用if語句或者while語句,可以直接在里面寫數(shù)字字符串之類的,它會自動(dòng)轉(zhuǎn)為boolean類型
alert(Boolean(3.14))//true
alert(Boolean(0))//false
alert(Boolean("nihao"))//true
alert(Boolean(""))//false
alert(Boolean(null))//false
alert(Boolean(undefined))//false
alert(Boolean(NaN))//false
alert(Boolean(Infinity))//true
4.5 String數(shù)據(jù)類型
?注意一下string有兩種屬性一種為傳統(tǒng)String,一種為Object;length可以測量字符串長度;
var s = new String();
var s2 = "你好啊"
alert(typeof s)//object
alert(typeof s2)//string
alert(s2.length) //3
注意區(qū)分substring和substr方法的區(qū)別:
alert("abcdefg".substr(2,4))//cdef
alert("abcdefg".substring(2,4))//cd
substr是輸出從下標(biāo)為2的開始輸出四個(gè)下標(biāo),而substring是從下標(biāo)為2的輸出到下標(biāo)為4的
4.6 關(guān)于Object類型
Object的定義和函數(shù)的定義一模一樣,只不過根據(jù)調(diào)用方式來判斷是函數(shù)還是類,如下:
function student(){
alert("student...")
}
//這樣就是調(diào)用函數(shù)
student();
//這樣就是創(chuàng)建類
var stu = new student();
JS中new對象和java不能說一模一樣只能說照搬過來,不過屬性不用在外面定義,直接用即可,如下:
function student(name,age){
/* this表示當(dāng)前對象 */
this.name = name;
this.age = age;
}
/* new 一個(gè)新的對象 */
var stu1 = new student("王德發(fā)",34);
alert(stu1.name)
alert(stu1.age)
?prototype屬性可以用來給任意一個(gè)類型擴(kuò)展函數(shù):
function product(name,price){
this.name = name;
this.price = price;
this.getName = function(){
return name;
}
}
var xigua = new product("西瓜",4.0);
alert(xigua.name)
alert(xigua.getName())
//給product類擴(kuò)展函數(shù)
product.prototype.getPrice = function(){
return this.price
}
alert(xigua.getPrice())
//給字符串?dāng)U展函數(shù)
String.prototype.suiyi = function(){
alert("給string類型擴(kuò)展一個(gè)函數(shù)叫suiyi")
}
"abc".suiyi();
4.7 NaN、undefined、null的區(qū)別
alert(typeof null)//object
alert(typeof undefined)//undefined
alert(typeof NaN)//number
alert(null == undefined)//true
alert(null == NaN)//false
alert(NaN == undefined)//false
值得注意的是JS中有“===”這種運(yùn)算符,它的意思是判斷值相等并且類型相等才會返回true?
4 函數(shù)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
/* 創(chuàng)建函數(shù) */
function hello(){
alert("hello");
}
//hello();
/* JS函數(shù)不需要指定返回類型 */
function sum(a, b){
console.log(a + b);
}
function sum2(a,b){
console.log(a+":"+b);
}
//JS代碼非常靈活
sum2()
sum2(1)
sum2(1,2)
sum2(1,2,3)
/* JS函數(shù)創(chuàng)建的第二種方式 */
welcome = function(){
alert("welcome")
}
</script>
<!-- 點(diǎn)擊按鈕,調(diào)用函數(shù),彈出hello -->
<input type="button" value="hello" onclick="hello()" />
<!-- 求和 -->
<input type="button" value="sum" onclick="sum(1,2)" />
<input type="button" value="welcome" onclick="welcome()" />
</body>
</html>
如果定義多個(gè)函數(shù),名稱相同,后面定義的會覆蓋前面定義的
5 事件
5.1 JS中有哪些常用的事件
( 1 ) blur失去焦點(diǎn)
( 2 ) change下拉列表選中項(xiàng)改變,或文本框內(nèi)容改變
( 3 ) click鼠標(biāo)單擊
( 4 ) dblclick鼠標(biāo)雙擊
( 5 ) focus獲得焦點(diǎn),
(6)keydown鍵盤按下
( 7 ) keyup鍵盤彈起
( 8 ) load頁面加載完畢
( 9 ) mousedown鼠標(biāo)按下
(10)mouseover鼠標(biāo)經(jīng)過
( 11 ) mousemove鼠標(biāo)移動(dòng)
( 12 ) mouseout鼠標(biāo)離開
( 13 ) mTouseup鼠標(biāo)彈起
( 14 ) reset表單重置
( 15 ) select文本被選定
( 16) submit表單提交
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
//alert(111)
</script>
</head>
<body onload="console.log('頁面全部加載完畢,加載完成')">
<!--JS中常用的事件:
( 1 ) blur失去焦點(diǎn)
( 2 ) change下拉列表選中項(xiàng)改變,或文本框內(nèi)容改變
( 3 ) click鼠標(biāo)單擊
( 4 ) dblclick鼠標(biāo)雙擊
( 5 ) focus獲得焦點(diǎn),
(6)keydown鍵盤按下
( 7 ) keyup鍵盤彈起
( 8 ) load頁面加載完畢
( 9 ) mousedown鼠標(biāo)按下
( 10 )mouseover鼠標(biāo)經(jīng)過
( 11 ) mousemove鼠標(biāo)移動(dòng)
( 12 ) mouseout鼠標(biāo)離開
( 13 ) mouseup鼠標(biāo)彈起
( 14 ) reset表單重置
( 15 ) select文本被選定
( 16 ) submit表單提交
-->
blur事件:<input type="text" onblur="console.log('失去焦點(diǎn)了')" /><br>
change事件:
<select name="grade" onchange="console.log('下拉列表發(fā)生變化了')">
<option value="gz">高中</option>
<option value="dz">大專</option>
<option value="bk">本科</option>
</select>
<br>
dbclick事件:<input type="button" value="雙擊我" ondblclick="console.log('鼠標(biāo)雙擊了')" /><br>
focus事件:<input type="text" onfocus="console.log('獲得焦點(diǎn)了')" /><br>
keydown和keyup事件:<input type="text" onkeydown="console.log('鍵盤按下')"
onkeyup="console.log('鍵盤彈起')"/><br>
mouse相關(guān)事件:<input type="button" value="mouse" onmousedown="console.log('鼠標(biāo)按下')"
onmouseover="console.log('鼠標(biāo)經(jīng)過')"
onmousemove="console.log('鼠標(biāo)移動(dòng)')"
onmouseout="console.log('鼠標(biāo)離開')"
onmouseup="console.log('鼠標(biāo)彈起')"/><br>
</body>
</html>
5.2 重點(diǎn)說說onload事件
因?yàn)镴S代碼是自上而下執(zhí)行,假如有這樣的代碼:
<script type="text/javascript">
var btnObj = document.getElementById("btn")
btnObj.onclick = function(){
alert("hello js...")
}
</script>
<input type="button" value="hello" id="btn" />
在上面獲取id,但是id在下面,這樣是獲取不到的,那怎么解決呢,將input語句放到上面即可,但是這樣又太呆了,這時(shí)就可以使用onload事件,它的作用是整個(gè)頁面加載完畢才會執(zhí)行,改造如下:
<script type="text/javascript">
window.onload = function(){
document.getElementById("btn").onclick = function(){
alert("hello")
}
}
</script>
<input type="button" value="hello" id="btn" />
?onload后面跟函數(shù),也就是說onload加載完成才會繼續(xù)執(zhí)行后面函數(shù),也就是說整個(gè)頁面加載完成后面的函數(shù)才會執(zhí)行,以后我們都按這個(gè)格式寫。
5.3 捕捉回車鍵
JS中input標(biāo)簽有個(gè)屬性onkeydown它可以檢測到鍵盤,也就是說只要按動(dòng)鍵盤任意一個(gè)鍵,它就會檢測到。而每一個(gè)鍵都是有對應(yīng)編號的,回車對應(yīng)的是13,有個(gè)屬性keyCode可以檢測到鍵盤每個(gè)鍵的值,這樣就能判斷我按得鍵是什么鍵了:
<script type="text/javascript">
window.onload = function(){
var usernameElt = document.getElementById("username")
usernameElt.onkeydown = function(event){
if(event.keyCode == 13){
alert("正在進(jìn)行驗(yàn)證。。。")
}
}
}
</script>
<input type="text" id="username" />
6 DOM編程
6.1 根據(jù)id獲取元素?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function getDivElt(){
var myDivElt = document.getElementById("mydiv")
console.log(myDivElt);
var myUsernameElt = document.getElementById("username")
console.log(myUsernameElt);
}
</script>
<div id="mydiv">
</div>
<input type="text" name="" id="username" value="" />
<input type="button" value="獲取節(jié)點(diǎn)" onclick="getDivElt()" />
</body>
</html>
6.2 獲取文本框value
原理就是先獲取到一個(gè)文本框的id,然后就可以獲取到它的value了,我們還可以修改value:
<script type="text/javascript">
window.onload = function(){
var btnElt = document.getElementById("btn")
btnElt.onclick = function(){
//獲取value
alert(document.getElementById("btn2").value)
//修改value
document.getElementById("btn2").value = "擬好啊"
}
}
</script>
<input type="text" id="btn2"/>
<input type="button" value="獲取文本框value" id="btn"/>
這樣我們可以做出這樣一個(gè)效果:兩個(gè)文本框,在一個(gè)文本框輸入內(nèi)容,點(diǎn)擊按鈕,讓這個(gè)文本框的內(nèi)容轉(zhuǎn)移到另一個(gè)文本框:
<script type="text/javascript">
window.onload = function(){
var copyElt = document.getElementById("copy")
copyElt.onclick = function(){
//獲取文本框1value給2
document.getElementById("u2").value = document.getElementById("u1").value
}
}
</script>
文本框1:<input type="text" id="u1" />
<input type="button" value="將文本框1內(nèi)容復(fù)制到2" id="copy"/>
<br />
文本框2:<input type="text" id="u2" />
6.3 innerHTML、innerText
innerHTML有兩個(gè)作用:一是可以拿出元素里的內(nèi)容,二是可以給元素賦值
innerText和innerHTML的區(qū)別是,Text顯示的是純文本,不管你輸入的是什么,都將原樣顯示,而HTML會識別出是否是HTML語言,會做相應(yīng)顯示
演示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function getContent(){
/* 先獲取元素 */
var div1Elt = document.getElementById("div1")
/* 再根據(jù)元素獲取其中的內(nèi)容 */
console.log(div1Elt.innerHTML)
/* 還可以給元素賦內(nèi)容 */
var div2Elt = document.getElementById("div2")
//div2Elt.innerHTML = "您好,張麻子。。"
div2Elt.innerHTML = "<font size='4' color='red'>用戶名不能為空捏</font>"
/* inner */
div2Elt.innerText = "<font size='4' color='red'>用戶名不能為空捏</font>"
}
</script>
<div id="div1">
擬好,王德發(fā)
</div>
<div id="div2">
</div>
<input type="button" value="hello" onclick="getContent()"/>
</body>
</html>
7 正則表達(dá)式
建議直接看網(wǎng)站上寫好的:正則表達(dá)式30分鐘入門教程
常見的正則表達(dá)式符號:
常用的元字符:
. | 匹配除換行符以外的任意字符 |
\w | 匹配字母或數(shù)字或下劃線或漢字 |
\s | 匹配任意的空白符 |
\d | 匹配數(shù)字 |
\b | 匹配單詞的開始或結(jié)束 |
^ | 匹配字符串的開始 |
$ | 匹配字符串的結(jié)束 |
常用的限定符:
代碼/語法 | 說明 |
---|---|
* | 重復(fù)零次或更多次 |
+ | 重復(fù)一次或更多次 |
? | 重復(fù)零次或一次 |
{n} | 重復(fù)n次 |
{n,} | 重復(fù)n次或更多次 |
{n,m} | 重復(fù)n到m次 |
常用的反義代碼:
代碼/語法 | 說明 |
---|---|
\W | 匹配任意不是字母,數(shù)字,下劃線,漢字的字符 |
\S | 匹配任意不是空白符的字符 |
\D | 匹配任意非數(shù)字的字符 |
\B | 匹配不是單詞開頭或結(jié)束的位置 |
[^x] | 匹配除了x以外的任意字符 |
[^aeiou] | 匹配除了aeiou這幾個(gè)字母以外的任意字符 |
正則表達(dá)式中的小括號優(yōu)先級較高
[1-9]表示1到9的任意1個(gè)數(shù)字(次數(shù)一次)
[A-Za-z0-9]表示A-Za-z0-9的任意一個(gè)字符
簡單的正則表達(dá)式要會寫:
QQ號:^[1-9][0-9]{4,}$
在JS中創(chuàng)建正則表達(dá)式在正則表達(dá)式前后加個(gè)“/”即可,然后得到表達(dá)式后使用test()方法驗(yàn)證。
驗(yàn)證郵箱是否填寫正確:
<script type="text/javascript">
window.onload = function(){
document.getElementById("test").onclick = function(){
//獲取email內(nèi)容
var emailValue = document.getElementById("email").value
//得到email正則表達(dá)式規(guī)則
var emailRegExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var ok = emailRegExp.test(emailValue)
if(ok){
document.getElementById("btn").innerText = "郵箱正確"
}else{
document.getElementById("btn").innerText = "郵箱錯(cuò)誤"
}
}
document.getElementById("email").onfocus = function(){
document.getElementById("btn").innerText = ""
}
}
</script>
<input type="text" id="email" />
<span style="color: red;font-size: 20px;" id="btn"></span>
<br />
<input type="button" value="驗(yàn)證郵箱" id="test"/>
補(bǔ)充trim函數(shù),它可以去掉字符串前后的所有空白
8 表單驗(yàn)證
要求如下:
注意:表單有個(gè)函數(shù)叫submit(),也就是說,使用表單可以直接提交表單,不用input標(biāo)簽中的submit也可以,這點(diǎn)很重要,因?yàn)槲覀円院缶筒挥胕nput標(biāo)簽提交了,經(jīng)典白學(xué),代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
span{
color: red;
font-size: 20px;
}
</style>
</head>
<body>
<script type="text/javascript">
//首先驗(yàn)證用戶名不能為空,6-14位之間,只能字母和數(shù)字,失去焦點(diǎn)驗(yàn)證
window.onload = function(){
//獲取span的id
var usernameErrSpan = document.getElementById("usernameErr")
var passwdErrSpan = document.getElementById("passwdErr")
var emailErrSpan = document.getElementById("emailErr")
var usernameElt = document.getElementById("username")
var passwd2Elt = document.getElementById("passwd2")
var emailElt = document.getElementById("email")
var submitBtnElt = document.getElementById("submitBtn")
//失去焦點(diǎn)
usernameElt.onblur = function(){
//去除空格
username = usernameElt.value.trim()
if(username === ""){
//用戶名為空
usernameErrSpan.innerText = "用戶名不能為空"
}else{
//用戶名不為空
//限制位數(shù)為6-14
if(username.length < 6 ||username.length > 14){
//位數(shù)不合法
usernameErrSpan.innerText = "用戶名位數(shù)要在6-14位之間"
}else{
//位數(shù)合法但是符號不合法
var regExp = /^[A-Za-z0-9]+$/;
var ok = regExp.test(username)
if(ok){
//合法
}else{
//不合法
usernameErrSpan.innerText = "用戶名只能使用字母或數(shù)字"
}
}
}
}
//獲得焦點(diǎn)
usernameElt.onfocus = function(){
//不合法才將內(nèi)容清空
if(usernameErrSpan.innerText != ""){
//spanErr有內(nèi)容說明是有錯(cuò)誤的,清空username表單
usernameElt.value = "";
}
usernameErrSpan.innerText = ""
}
//驗(yàn)證密碼
passwd2Elt.onblur = function(){
//判斷密碼輸入是否一樣
var passwd1Elt = document.getElementById("passwd1")
var passwd1 = passwd1Elt.value
var passwd2 = passwd2Elt.value
if(passwd1 == passwd2){
//密碼一樣
}else{
//密碼不一致
//報(bào)錯(cuò)
passwdErrSpan.innerText = "密碼不一致,請重新填寫!"
}
}
//驗(yàn)證郵箱
emailElt.onblur = function(){
var email = emailElt.value
var emailRegExp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var ok = emailRegExp.test(email)
if(ok){
//郵箱沒問題
}else{
//郵箱錯(cuò)誤
emailErrSpan.innerText = "郵箱格式錯(cuò)誤!"
}
}
emailElt.onfocus = function(){
emailErrSpan.innerText = ""
}
//注冊
//注冊前要判斷是否輸入的都合法才能提交注冊
submitBtnElt.onclick = function(){
//觸發(fā)focus和blur事件,不需要人工操作,JS代碼自動(dòng)觸發(fā)
usernameElt.focus()
usernameElt.blur()
passwd2Elt.focus()
passwd2Elt.blur()
emailElt.focus()
emailElt.blur()
var userFormElt = document.getElementById("userForm")
if(usernameErrSpan.innerText == "" && passwdErrSpan.innerText == ""
&& emailErrSpan.innerText == ""){
//合法提交
userFormElt.submit();
}
}
}
</script>
<form id="userForm" action="http://localhost:8080/submit" method="get">
用戶名:<input type="text" name="username" id="username" /><span id="usernameErr"></span><br>
密碼:<input type="text" name="passwd1" id="passwd1" /><br>
確認(rèn)密碼:<input type="text" name="passwd2" id="passwd2" /><span id="passwdErr"></span><br>
郵箱:<input type="text" name="email" id="email" /><span id="emailErr"></span><br>
<input type="button" value="注冊" id="submitBtn" />
<input type="reset" value="重置" />
</form>
</body>
</html>
這樣的表單驗(yàn)證肯是不完善的,可以繼續(xù)改進(jìn),但也挺不錯(cuò)了。?
9 復(fù)選框全選與取消全選
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body onload="bindClick()">
<script type="text/javascript">
function checkAll(){
var firstchkElt = document.getElementById("firstchk")
//alert(firstchkElt.checked)
var hobbys = document.getElementsByName("hobby")
for (var i = 0; i < hobbys.length; i++) {
hobbys[i].checked = firstchkElt.checked
}
}
function bindClick(){
var hobbychks = document.getElementsByName("hobby")
for (var i = 0; i < hobbychks.length; i++) {
hobbychks[i].onclick = function(){
//alert(111)
//當(dāng)復(fù)選框數(shù)量和選中的數(shù)量一樣就是全選中,否則不是
var count = hobbychks.length;
var countChks = 0;
for (var i = 0; i < hobbychks.length; i++) {
if(hobbychks[i].checked){
countChks++
}
}
document.getElementById("firstchk").checked = (count == countChks)
}
}
}
</script>
<input type="checkbox" id="firstchk" onclick="checkAll()" /><br>
<input type="checkbox" name="hobby" value="1" /> 抽煙<br>
<input type="checkbox" name="hobby" value="2" /> 喝酒<br>
<input type="checkbox" name="hobby" value="3" /> 燙頭<br>
<input type="checkbox" name="hobby" value="4" /> 蹦迪<br>
<input type="checkbox" name="hobby" value="5" /> 睡覺<br>
</body>
</html>
10 周期函數(shù)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var nowTime = new Date()
document.write(nowTime)
document.write("<br>")
//轉(zhuǎn)換為本地語言環(huán)境的時(shí)間格式
nowTime = nowTime.toLocaleString();
document.write(nowTime)
document.write("<br>")
document.write("<br>")
//怎么獲取毫秒數(shù)?(從1970年1月1日00:00:00 000到系統(tǒng)當(dāng)前時(shí)間的總毫秒數(shù))
document.write(new Date().getTime())
document.write("<br>")
document.write("<br>")
function printNowTime(){
var time = new Date()
var strTime = time.toLocaleTimeString()
document.getElementById("timeDiv").innerHTML = strTime
}
//重點(diǎn)在這
//每隔1秒調(diào)用printNowTime函數(shù)一次,實(shí)現(xiàn)實(shí)時(shí)展示時(shí)間效果
function start(){
//1000是指1000毫秒,注意前面不要加var,那就是局部變量了
t = window.setInterval("printNowTime()",1000)
}
//但我想停止時(shí)間展示
function stop(){
window.clearInterval(t)
}
</script>
<input type="button" value="獲取當(dāng)前時(shí)間" onclick="start()" />
<input type="button" value="停止時(shí)間獲取" onclick="stop()" />
<div id="timeDiv"></div>
</body>
</html>
11 BOM相關(guān)
window.location可以獲取到當(dāng)前頁面的地址欄地址,當(dāng)然也可以隨意修改這個(gè)地址,接著就會跳轉(zhuǎn)到對應(yīng)頁面:
<script type="text/javascript">
function goBaidu(){
//window.location = "http://baidu.com"
document.location = "http://baidu.com"
}
</script>
<input type="button" value="百度" onclick="goBaidu()" />
history.back()可以實(shí)現(xiàn)后退,不過只能實(shí)現(xiàn)當(dāng)前頁面,如果跳轉(zhuǎn)到新的頁面自然無法后退,就和瀏覽器的左上角的后退功能一樣:
<input type="button" value="進(jìn)入一個(gè)頁面" onclick="window.open('20-BOM相關(guān)附件.html','_self')"/>
<a href="20-BOM相關(guān)附件.html">進(jìn)入一個(gè)頁面</a>
<h1>我是新頁面</h1>
<br>
<input type="button" value="后退" onclick="window.history.back()"/>
window.open("url")可以打開一個(gè)頁面;window.alert('")會彈出消息框,window.confirm("")也是彈出消息框,不過它可以進(jìn)行確認(rèn)和取消操作,確認(rèn)返回true取消返回false:
<input type="button" value="打開百度(新窗口)" onclick="window.open('http://www.baidu.com')"/>
<input type="button" value="打開百度(當(dāng)前窗口)" onclick="window.open('http://www.baidu.com','_self')"/>
<input type="button" value="打開百度(新窗口)" onclick="window.open('http://www.baidu.com','_black')"/>
<br />
<br>
<script type="text/javascript">
function del(){
if(window.confirm("親,確認(rèn)刪除嗎")){
alert("正在刪除中....")
}
}
</script>
<input type="button" value="彈出消息框" onclick="window.alert('消息框')" />
<input type="button" value="彈出確認(rèn)框" onclick="del()" />
以下代碼可以用來將一個(gè)窗口轉(zhuǎn)為頂級窗口,什么意思呢,就是這個(gè)頁面可能是嵌在一個(gè)頁面里的,我想讓它出來并且是在最上面的頁面:
if(window.top != window.self){
window.top.location = window.self.location
}
12 JSON
什么是JSON,有什么用?
JavaScript Object Notation(JavaScript對象標(biāo)記),是一種數(shù)據(jù)交換格式。比如系統(tǒng)A和系統(tǒng)B交換格式可以使用JSON,它的特點(diǎn)是體積小,易解析
在實(shí)際開發(fā)中有兩種交換格式,其一是JSON,其二是XML。XML體積較大,解析麻煩,但是它語法嚴(yán)謹(jǐn),通常銀行相關(guān)業(yè)務(wù)使用XML。
JSON語法格式非常簡單,如下:JSON就是一種對象
//創(chuàng)建一個(gè)student對象
var studentObj = {
"sno":"110",
"name":"王德發(fā)",
"sex":"男"
}
alert(studentObj.name)
//創(chuàng)建student數(shù)組
var students = [
{"sno":"110","sname":"張麻子","sex":"男"},
{"sno":"120","sname":"馬邦德","sex":"男"},
{"sno":"114","sname":"黃四郎","sex":"男"}
]
for(var i = 0;i < students.length ;i++){
var stuObj = students[i]
alert(stuObj.sname)
}
既然JSON是一種對象,當(dāng)然也可以像java那樣套娃
eval函數(shù):
它可以將字符串當(dāng)做一段JS代碼解析并執(zhí)行
window.eval("var i = 100")
alert(i)
//上面兩行就 相當(dāng)于下面兩行
var j = 100;
alert(j)
那么這玩意到底有什么用呢?當(dāng)我們使用java連接數(shù)據(jù)庫得到數(shù)據(jù)并將數(shù)據(jù)拼接成JSON格式的“字符串”,將JSON格式字符串響應(yīng)到瀏覽器。也就是說,java響應(yīng)到瀏覽器的上的僅僅是字符串,還不是JSON對象。可以用eval函數(shù)將JSON格式的字符串轉(zhuǎn)為JSON對象
//java程序發(fā)來的JSON格式的字符串,要將雙引號轉(zhuǎn)義,因?yàn)閔tml雙引號里面不能再有雙引號
var fromJava = "{\"sno\":\"110\",\"sname\":\"張麻子\",\"sex\":\"男\(zhòng)"}"
window.eval("var jsonObj =" + fromJava )
alert(jsonObj.sno + "," + jsonObj.sname)
?訪問JSON還有另一種方式:
alert(jsonObj["sex"])
在JS中[]和{}有啥區(qū)別,中括號是數(shù)組,大括號是JSON文章來源:http://www.zghlxwxcb.cn/news/detail-484079.html
下面模擬如何將java獲取到的數(shù)據(jù)顯示到瀏覽器上文章來源地址http://www.zghlxwxcb.cn/news/detail-484079.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//json中有一些數(shù)據(jù)
var data = {
"total":4,
"emps":[
{"empno":123,"ename":"jack","sal":4000},
{"empno":124,"ename":"simth","sal":6000},
{"empno":125,"ename":"black","sal":4000},
{"empno":126,"ename":"rose","sal":70000}
]
}
//把上面數(shù)據(jù)放到下面的table中
window.onload = function(){
var displayEmpsElt = document.getElementById("displayEmps")
displayEmpsElt.onclick = function(){
//拿到員工信息
var emps = data.emps
var html = "";
//循環(huán)得到
for(var i = 0;i < emps.length;i++){
html+="<tr>"
html+="<td>"+emps[i].empno+"</td>"
html+="<td>"+emps[i].ename+"</td>"
html+="<td>"+emps[i].sal+"</td>"
html+="</tr>"
}
document.getElementById("emptbody").innerHTML = html
document.getElementById("count").innerText = data.total
}
}
</script>
<input type="button" id="displayEmps" value="展示員工信息" />
<hr>
<table border="1px" width="50%">
<tr>
<th>員工編號</td>
<th>員工姓名</td>
<th>員工工資</td>
</tr>
<tbody id="emptbody">
<!-- <tr>
<td>1213</td>
<td>張三</td>
<td>4500</td>
</tr>
<tr>
<td>1213</td>
<td>王德發(fā)</td>
<td>4700</td>
</tr>
<tr>
<td>1214</td>
<td>李四</td>
<td>4600</td>
</tr> -->
</tbody>
</table>
總共<span id="count">0</span>條數(shù)據(jù)
</body>
</html>
到了這里,關(guān)于Web前端-JavaScript的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!