JavaScript配合button.onclick()使用总结

Html加载顺序是从上往下加载,如果script中含有引用js脚本,则应该将此script放在head标签里面,这样可是保证此页面都可以引用js脚本内容。如果想在script中设置button.onclick()事件,则此script应放在button声明之后。

例子:index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
    contentType="text/html; charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>javaScript和button.onclick()事件</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<!-- 全文相关的script脚本(包括引用的script文件)放在head标签中 -->
<script type="text/javascript" src="include.js">
    function fun1() {
        alert("第一种script方式显示时间是:" + Date());
    }
</script>
</head>

<body>
    <button id="button11" onclick="fun1()">第一种script方式显示时间</button>
    <button id="button12" onclick="fun2()">通过引用js文件显示时间</button>
    <button id="button2">第二种script方式显示时间</button>
    <button id="button3">第三种script方式显示时间</button>
    <script>
        document.getElementById("button2").onclick = function() {
            displayDate()
        };
        document.getElementById("button3").onclick = displayDate2;
        function displayDate() {
            document.getElementById("demo").innerHTML = "第二种script方式显示时间是:"
                    + Date();
        }
        function displayDate2() {
            document.getElementById("demo2").innerHTML = "第三种script方式显示时间是:"
                    + Date();
        }
    </script>
    <br>时间一:
    <p id="demo"></p>
    时间二:
    <p id="demo2"></p>
</body>
</html>

include.js

    function fun2() {
        alert("通过引用js文件显示时间是:" + Date());
    }

输入网址:http://localhost:8080/Test/index.jsp,截图如下

原文地址:https://www.cnblogs.com/SaraMoring/p/5740958.html