1.首先,我们来看一下经常使用的添加事件的方式:
<input type="button" id="btn" value="click me!" onclick="shao();" />
<script type="text/javascript">
function shao() {
alert("msg is showing!");
}
</script>我们最常用的是为元素添加onclick元素属性的方式来添加事件
这种方法的弊端是:
只能为一个事件处理函数,在事件处理函数方法中,获取事件对象的方式不同.
jQuery中的事件
ready事件:
当页面加载完成后,来执行function:
<script>
$(document).ready(function(e){
alert(document.getElementById("aa").innerHTML);
//若是要写function方法,不可以在里面写
})
//要在外面写
</script>这样写在哪里都可以调用到这个方法;
鼠标事件:
<script>
$("#aa").click(function(){
alert("点击事件");
})
$("#aa").dblclick(function(){
alert("双击事件");
})
$("#aa").mouseover(function(){
alert("鼠标移上")
});
$("#aa").mouseout(function(){
alert("鼠标离开");
})
$("#aa").mousemove(function(){
alert("鼠标移动");
})
$("#aa").mouseup(function(){
alert("鼠标抬起");
})
$("#aa").mousedown(function(){
alert("鼠标按下");
})
键盘按键按下:给id加没有作用,需要给整个页面加所以用$(document)
$(document).KeyEvent(function(){
alert("鼠标离开");
})
</script>
表单元素事件:
<script>
$("#shao").focus(function(){
alert("获得焦点");
})
$("#shao").blur(function(){
alert("失去焦点");
})
$("#shao").change(function(){
alert("值发生变化,change事件");
})
$("#shao").keydown(function(){
alert("键盘按下");
})
</script>2.绑定事件(挂事件):
可以动态的改变按钮的事件;
什么是动态绑定?
动态绑定是指动态添加的DOM节点或者html元素,他们最开始时运行的时候是不存在的。如果要给这些动态加入的节点增加事件,就必须要用jquery的on方法来绑定事件。
bind()向匹配元素添加一个或多个事件处理器。
使用方式:
$(selector).bind(event,data,function)注:bind()函数只能针对已经存在的元素进行事件的设置
代码:首先写两个按钮:










