JS是一種腳本語言
javascript
1.JS實現HTML輸出
html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title> This is my HTML</title> </head> <body> <script type="text/javascript"> document.write("JS實現HTML輸出"); </script> </body> </html>
2.JS實現對事件做出反應
java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title> This is my HTML</title> </head> <body> <button type="button" onclick="alert('點擊了按鈕')">按鈕</button> </body> </html>
3.JS改變HTML內容
測試
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title> This is my HTML</title> </head> <body> <p id="changeContent">本來輸出的內容</p> <script type="text/javascript"> function changeHTMLContent() { //找到元素(很明顯,本例子的元素是p) x=document.getElementById("changeContent"); //改變的內容 x.innerHTML="這是替換的內容"; //改變顏色 x.style.color = "#00ff00"; } </script> <button type="button" onclick="changeHTMLContent()">按鈕</button> </body> </html>
4.JS驗證輸入
ui
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title> This is my HTML</title> </head> <body> <p>驗證輸入的是否爲數字,若是不爲數字,彈出提示框提示</p> <input id="test" type="text"> <script type="text/javascript"> function check() { var x = document.getElementById("test").value; if (x == "" || isNaN(x)) { alert("請輸入數字"); }; } </script> <button type="button" onclick="check()">點擊測試</button> </body> </html>