JavaScript Day 3
阿新 • • 發佈:2021-10-06
JavaScript Day 3
JavaScript物件
-
String物件
var string = new String('hello'); alert(typeof(string)+' '+string);
-
Array物件
var array1=new Array(); array1[0]=0; array1[1]=1; var array2=[1,2]; var array3=new Array(1,2,3);
-
Date物件
var date1 = new Date(); var date2 = new Date(milliseconds); var date3 = new Date(dateString); var date4 = new Date(year, month, day, hours, minutes, seconds, milliseconds);
-
Math物件
var num=Math.random();// 返回 0 ~ 1 之間的隨機數。 var max=Math.max(12,34,-90,9);//返回 n個數值中的最大值。 var min=Math.min(12,34,-90,9);//返回 n個數值中的最小值。
JavaScript的函式
常用全域性函式
- isNaN(param)
- parseFloat(String)
- parseInt(string,radix)
自定義函式
function 自定義函式名稱(引數列表){ //函式體 } //函式的形參直接寫引數名稱,不需要宣告型別,即不需要寫var. //函式的返回取決於函式體中是否有return關鍵字.
匿名函式
var fun = function () {
alert("fun!");
}
fun();
JavaScript變數的作用域
- 區域性 JavaScript 變數
在 JavaScript 函式內部宣告的變數(使用 var)是 變數,所以只能在函式內部訪問,在不同的函式中可以宣告名稱相同變數,因為區域性變量出該函式就失效了。 - 全域性 JavaScript 變數
在函式外宣告的變數是 變數,網頁上的所有指令碼和函式都能訪問它。
<script> var userId = 1001; //全域性變數:整個script指令碼中都可用,要注意先後順序 function printMessage() { var userName = "李白";//區域性變數:只在當前函式中生效 document.write(userId);//使用全域性變數的時候,保證使用(方法被呼叫)之前定義並賦值 document.write(message); printMessage(); </script> <script> function printMessage2() { var userName2 = "李白2"; document.write(userId);//這裡也可以使用userId //document.write(userName1);//錯誤:呼叫不到printMessage函式中的區域性變數 document.write(userName2);//正確:可以使用自己函式中的區域性變數 } </script>
變數的生命週期
JavaScript 變數的生命期從它們被宣告的時間開始。
區域性變數會在函式執行以後被刪除。全域性變數會在頁面關閉後被刪除。
JavaScript自定義物件
var Student =
{
name: "LIN",
age: 12,
height: 177.5,
study: function () { alert("Study!") }
}
Student.study();
alert(Student.name);
//訪問物件的屬性
//方式1:
var n = Student.name;
//方式2:
var n2 = Student["name"];
Window–瀏覽器物件模型(BOM)
-
window物件Window 物件 (w3school.com.cn)
if(window.confirm("confirm test")==true)alert("yes"); else alert('no');
<a href="javascript:window.open('https://www.baidu.com')">開啟百度</a> <a href="javascript:window.open('index.html')">開啟-index</a> <a href="javascript:window.close()">關閉當前頁面</a>
定時器操作
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="/test.js"></script> </head> <body> <script> function fun() { document.getElementById("demo").innerHTML = new Date().toUTCString(); } window.setInterval("fun()", 1000); </script> <p id="demo"></p> </body> </html>
-
history物件
<a href="javascript:window.history.forward()">前進</a> <a href="javascript:window.history.back()">後退</a> <a href="javascript:window.history.go(1)">前進go</a> <a href="javascript:window.history.go(-1)">後退go</a>
-
location物件
<a href="javascript:alert(window.location.href)">獲取當前頁面的URL地址</a> <a href="javascript:window.location.reload()">重新整理</a><br /> <a href="javascript:window.location.replace('index.html')">跳轉到index</a><br /> <a href="javascript:location.replace('https://www.baidu.com')">跳轉到百度</a><br />
JavaScript之事件
onchange HTML 元素改變
onclick 使用者點選 HTML 元素
onmouseover 使用者在一個HTML元素上移動滑鼠
onmouseout 使用者從一個HTML元素上移開滑鼠
onkeydown 使用者按下鍵盤按鍵
onload 瀏覽器已完成頁面的載入
onfocus 元素獲取焦點時觸發
onblur 元素失去焦點時觸發
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/test.js"></script>
</head>
<body>
<script>
function fun1() {
alert('選擇的內容發生了變化');
}
function fun2() {
alert("觸發了單擊事件");
}
function fun3() {
document.getElementById("btn").innerHTML = "滑鼠移動到按鈕上了";
}
function fun4() {
document.getElementById("btn").innerHTML = "點選我試試";
}
function fun5() {
alert("鍵盤按下了");
}
function fun6() {
alert("獲取到了焦點");
}
function fun7() {
alert("input失去了焦點");
}
function myLoad() {
alert("頁面載入完畢");
}
</script>
<body onload="myLoad()">
<input id="userName" onkeydown="fun5()" onfocus="fun6()" onblur="fun7()" />
<input id="password" type="password" />
<button id="btn" type="button" onclick="fun2()" onmouseover="fun3()" onmouseout="fun4()">點選我試試</button>
<select id="month" onchange="fun1()">
<option>1月份</option>
<option>2月份</option>
</select>
</body>
</body>
</html>
JavaScript之DOM模型
通過可程式設計的物件模型,JavaScript 獲得了足夠的能力來建立動態的 HTML:
- JavaScript 能夠改變頁面中的所有 HTML
- 元素 JavaScript 能夠改變頁面中的所有 HTML 屬性
- JavaScript 能夠改變頁面中的所有 CSS 樣式
- JavaScript 能夠對頁面中的所有事件做出反應
document.getElementById() 返回對擁有指定 id 的第一個物件的引用。
document.getElementsByClassName() 返回文件中所有指定類名的元素集合,作為 NodeList 物件
document.getElementsByTagName() 返回帶有指定標籤名的物件集合
document.getElementsByName() 返回帶有指定名稱的物件集合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function myLoad() {
//如果有重名的ID元素,獲取到的是第一個元素)
var div = document.getElementById("myDiv");
console.log(div);
//根據指定的類樣式的名稱獲取元素,返回集合
var list = document.getElementsByClassName("demo");
console.log("根據類樣式的名稱獲取到的元素的集合長度是:" + list.length); for (var i = 0; i < list.length; i++) {
console.log(list[i]);
}
//根據指定HTML標籤名稱獲取元素,返回集合
var list2 = document.getElementsByTagName("li");
console.log("根據標籤的名稱獲取到的元素的集合長度是:" + list2.length);
for (var i = 0; i < list2.length; i++) {
console.log(list2[i]);
}
//根據指定HTML元素的name屬性獲取元素,返回集合
var list3 = document.getElementsByName("myli"); console.log("根據標籤的名稱屬性獲取到的元素的集合長度是:" + list3.length);
for (var i = 0; i < list3.length; i++) {
console.log(list3[i]);
}
}
</script>
<body onload="myLoad()">
<p class="demo"></p>
<div id="myDiv" class="demo">
div
</div>
<ul class="demo">
<li>li11111111111</li>
<li name="myli">li11111111111</li>
<li>li11111111111</li>
<li name="myli">li11111111111</li>
</ul>
</body>
</body>
</html>
修改 HTML 內容和屬性
//修改 HTML 元素屬性的語法:
//方式1:
document.getElementById(id).attribute=新屬性值;
//方式2:
document.getElementById(id).setAttribute(屬性名,屬性值);
修改 HTML 元素的css
document.getElementById("myli").style.color="blue";
document.getElementById("myli").style.fontFamily="微軟雅黑";
document.getElementById("myli").style.fontSize="24px";
HTML DOM 元素
建立新的 HTML 元素
要建立新的 HTML 元素 (節點)需要先建立一個元素,然後在已存在的元素中新增
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
var num = 0;
function createNewP() {
var newP = document.createElement("p");
newP.appendChild(document.createTextNode("" + num++));
document.getElementById("div1").appendChild(newP);
}
function createNewP2() {
var newP = document.createElement("p");
newP.appendChild(document.createTextNode("" + num++));
document.getElementById("div1").insertBefore(newP, document.getElementById("p1"));
}
</script>
</head>
<body>
<button type="button" onclick="createNewP()">動態新增一個元素-- appendChild</button>
<button type="button" onclick="createNewP2()">動態新增一個元素-- insertBefore</button>
<div id="div1">
<p id="p1">這是段落1</p>
</div>
</body>
</html>
替換 HTML 元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function changeElemnt() {
var num = 'hello';
var newp = document.createElement('p1').appendChild(document.createTextNode(num));
document.getElementById('div1').replaceChild(newp, document.getElementById('p1'));
}
</script>
</head>
<body>
<div id="div1">
<p id="p1">1</p>
</div>
<button type="button" onclick="changeElemnt()">+1</button>
</body>
</html>
刪除HTML元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function changeElemnt() {
document.getElementById('div1').removeChild(document.getElementById('p1'));
}</script>
</head>
<body>
<div id="div1">
<p id="p1">1</p>
</div>
<button type="button" onclick="changeElemnt()">removeChild</button>
</body>
</html>
表單驗證
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表單驗證</title>
<script>
function validateName(){
//所有的表單項元素都value屬性
var name=document.getElementById("userName").value;
var msg=document.getElementById("nameMsg");
if(name==null || name ==""){
msg.innerHTML="使用者名稱不能為空!";
msg.style.color="red";
return false;
} else if(name.length<6){
msg.innerHTML="使用者名稱長度必須為大於6的!";
msg.style.color="red";
return false;
}
msg.innerHTML="使用者名稱可用"; msg.style.color="green";
return true;
}
function validatePwd(){
var password1=document.getElementById("password1").value;
var msg=document.getElementById("pwdMsg1");
if(password1==null || password1 ==""){
msg.innerHTML="密碼不能為空!"; msg.style.color="red";
return false;
} else if(password1.length<8){
msg.innerHTML="密碼的長度必須為大於8的!";
msg.style.color="red";
return false;
}
msg.innerHTML="密碼合法"; msg.style.color="green";
return true;
}
function confirmPwd(){
var pwd1=document.getElementById("password1").value;
var pwd2=document.getElementById("password2").value;
var msg=document.getElementById("pwdMsg2");
if(pwd1!=pwd2){
msg.innerHTML="兩次輸入的密碼不一致!";
msg.style.color="red";
return false;
}
msg.innerHTML="兩次輸入的密碼一致";
msg.style.color="green";
return true;
}
function validateGender(){
var gender=document.getElementById("gender").value;
if(gender==-1){
alert("性別為必選項!");
return false;
}
return true;
}
function register(){
return validateName()&&validatePwd()&&confirmPwd()&&validateGender();
}
</script>
</head>
<body>
<form action="提交.html" method="get" onsubmit="return register()">
*使用者名稱:<input type="text" id="userName" placeholder="請輸入使用者名稱" onblur="validateName()" />
<span id="nameMsg">使用者名稱長度至少6位</span><br />
*密碼:<input type="password" id="password1" placeholder="請輸入密碼" onblur="validatePwd()"/>
<span id="pwdMsg1">密碼長度至少8位</span><br />
*確認密碼:<input type="password" id="password2" placeholder="請確認密 碼" onblur="confirmPwd()" />
<span id="pwdMsg2">確認密碼與密碼一致</span><br />
*性別:<select id="gender">
<option value="-1">請選擇性別</option>
<option value="0">女</option>
<option value="1">男</option>
</select><br /><br />
<button type="submit">註冊</button>
<button type="reset">重置</button>
</form>
</body>
</html>
正則表示式
var reg=new RegExp(/正則表示式主體/,修飾符(可選)); 或更簡單的方法
var reg=/正則表示式主體/修飾符(可選);
案例:
var reg=new RegExp(/kaikeba/i);
var reg = /kaikeba/i; //此處定義了一個一個正則表示式。 kaikeba 是一個正則表示式主體 (用於檢索)。
i 是一個修飾符 (搜尋不區分大小寫)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>var pattern = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
str = window.prompt("郵箱驗證");
alert(pattern.test(str));
</script>
</head>
<body>
</body>
</html>