JS 的 document 內置對象
把 html 中每個標簽看成一個節點, 通過 js 將這些節點獲取出來
使用 JS 的 document 內置對象(對象有自己的屬性和方法),
內置對象就是已經創建好的對象, 我們只需要直接使用即可
方法:
document.getElementById("id屬性")
根據元素的 id 值獲取對象, 返回值是一個對象
innerHTML
獲取節點對象下 的所有 html 代碼.
document.getElementsByTagName("標簽名");
根據標簽嗎獲取對象, 返回一個集合(數組)
isNaN(字符串)
判斷一個字符串是否是純數字, 不是純數字返回true, 反之返回 false
Demo: 根據 id 值獲取元素節點對象
html:
1 <body> 2 <div id = "div1"> 3 <p> 4 很快就放假了! 5 </p> 6 </div> 7 </body> 8 </html> 9 <script src="index.js"></script>
js:
var node = document.getElementById("div1"); console.log(node.innerHTML);
Demo: 根據標簽名獲取元素節點
html:
<body> 用戶名: <input type="text" name="username" value="張三"> 密 碼 : <input type="password" name="pwd" value="1234"> 電 話 : <input type="text" name="iphone" value="110"> </body> </html> <script src="index.js"></script>
js:
1 var inputs = document.getElementsByTagName("input"); 2 console.log("用戶名: " + inputs[0].value); 3 console.log(" 密 碼: " + inputs[1].value); 4 var iphone = inputs[2].value; 5 //判斷一個字符串是否是純數字 6 if (isNaN(iphone)){ //不是純數字返回true, 是純數字返回false 7 alert("電話不是純數字") 8 }else{ 9 alert("電話是純數字") 10 }
Demo: 根據 class 獲取元素節點
html:
<body> <p class="wuyi"> <h1>1.五一快樂</h1> </p> <p class="wuyi"> <h1>2.五一快樂</h1> </p> <p class="wuyi"> <h1>3.五一快樂</h1> </p> <p class="wuyi"> <h1>4.五一快樂</h1> </p> </body> </html> <script src="index.js"></script>
js:
var ps=document.getElementsByClassName('wuyi'); //遍歷循環 ps for(var i=0;i<ps.length;i++){ console.log(ps[i]); }
Demo: 在文本框輸入兩個數, 然后計算出值之后輸出
html:
<body> A的值: <input type="text" name="numA"> B的值: <input type="text" name="numB"> A的值: <input type="text" name="numC"> <button type="button" onclick="addSum()">開始計算</button> </body> </html> <script src="index.js"></script>
js:
1 function addSum(){ 2 //獲取文本框中的值 3 var inputs=document.getElementsByTagName('input'); 4 var numA=inputs[0].value; 5 var numB=inputs[1].value; 6 //將字符串換成數字 7 var sum=parseInt(numA)+parseInt(numB); 8 //將計算的值填寫到第三個input中 9 inputs[2].value=sum; 10 }