1、javascript指令要在<script></script>中
2、document.writer("输出。。文字");
1 <!DOCTYPE html> 2 <html> 3 <body> 4 5 <p> 6 JavaScript 能够直接写入 HTML 输出流中: 7 </p> 8 9 <script> 10 document.write("这是第一个java Script"); 11 </script> 12 </body> 13 </html>
3、<button type="button" οnclick="alert('welcome')">click here</button>
4、改变指定id的元素
改变文字
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script> 5 function change(){ 6 x = document.getElementById("demo"); 7 x.innerHTML="hello getElementById and innerHTML"; 8 } 9 </script> 10 </head> 11 <body> 12 13 <h1>我的第一段 JavaScript</h1> 14 <p id="demo">这段会被改变点击按钮以后</p> 15 16 17 <button type="button" οnclick="change()">click</button> 18 19 20 </body> 21 </html>
改变样式
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script> 5 function change(){ 6 x = document.getElementById("demo"); 7 x.style.color="#ff0000"; 8 } 9 </script> 10 </head> 11 <body> 12 13 <h1>我的第一段 JavaScript</h1> 14 <p id="demo">这段会被改变点击按钮以后</p> 15 16 17 <button type="button" οnclick="change()">click</button> 18 19 20 </body> 21 </html>
5.验证输入:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script> 5 function change(){ 6 var x = document.getElementById("demo").value; 7 if(x==""||isNaN(x)){ 8 alert('not a numeric'); 9 } 10 } 11 </script> 12 </head> 13 <body> 14 请输入数字,如果不是数字会弹出对话框: 15 <br/> 16 <input id="demo" type="text"></input> 17 <button type="button" οnclick="change()">click here</button> 18 </body> 19 </html>
6.
也可以把脚本保存到外部文件中。外部文件通常包含被多个网页使用的代码。
外部 JavaScript 文件的文件扩展名是 .js。
如需使用外部文件,请在 <script> 标签的 "src" 属性中设置该 .js 文件:
提示:外部脚本不能包含 <script> 标签。