有四種方法:
方法1: 在<script>標簽內直接寫代碼
<body> <button id="btn">click</button> <script> document.getElementById("btn").onclick = function(){ alert("click"); } </script> </body>
方法2: 在使用<script>標簽的src屬性引入外部js文件
// test.js // document.getElementById("btn").onclick = function(){ alert("hello") }; // test.html <body> <button id="btn">click</button> <script src="./test.js"> 因為src引入了外部文件, 因此寫在標簽中的代碼不會執行. </script> </body>
方法3: 通過事件屬性
<body> <input type="text" onblur="alert(this.value)" /> </body>
方法4: 使用URL協議
<body> <a href="javascript:alert('hello')">click</a> </body>
