有四种方法:
方法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>