以点击事件为例,为元素绑定点击事件的方式为:
方式1(js版):
<head>
<script>
function fn(){
alert("input按钮被点击了...");
}
</script>
</head>
<body>
<input onclick="fn()" type="button" value="点我~!" />
</body>
方式2(js版):
<head>
<script>
window.onload = function(){
//获取id为btn的元素
var btn = document.getElementById("btn");
btn.onclick = function(){
alert("input按钮被点击了...");
}
}
</script>
</head>
<body>
<input id="btn" type="button" value="点我~!" />
</body>
方式3(jQuery版):
<head>
<script>
$(function(){
//当点击btn按钮时,触发点击事件执行其中的函数
$("#btn").click( function(){
alert("input按钮被点击了...");
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="点我~!" />
</body>