很多事件是要通过js来响应,js现在也是越来越强大,打通前端后端。
js有三种位置,写在前面,后面或者独立成一个文件,然后引用。
js有三种简单的程序结构,顺序结构,if跳转结构和for循环结构。
先看事件,事件的函数响应和程序的顺序结构:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <html> <body> <p id="s">用户已登录</p> <script language=javascript> function checkStu() { //函数位置可以写在三个地方 alert ("欢迎您,小狮子");//弹窗,最好的检查代码是否有误的方式。 alert ("how are you going today"); alert ("have a good day, see you"); document.getElementById("s").innerHTML="用户小狮子已登录"; //向页面输出内容 } </script> <input type="text" name="username"> <input type="button" value="登录" onclick="checkStu()"> <!--onclick触发事件,checkStu()调用函数--> </form> </body> </html> |
如果是要把js单独写在一个文件里,则在html文件里的代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html> <body> <p id="s">用户已登录</p> <script src="login.js"></script> <input type="text" name="username"> <input type="button" value="登录" onclick="checkStu()"> </body> </html> |
注意,原来script里面的内容没有了,转而变为对login.js的调用。
在login.js文件中的代码是:
1 2 3 4 5 6 | function checkStu() { //函数位置可以写在三个地方 alert ("欢迎您,小狮子");//弹窗,最好的检查代码是否有误的方式。 alert ("how are you going today"); alert ("have a good day, see you"); document.getElementById("s").innerHTML="用户小狮子已登录"; //向页面输出内容 } |