为元素绑定事件
<script src="jquery-1.12.1.js"></script>
<script>
$(function(){
//第一种写法
//为按钮绑定鼠标进入,鼠标离开,点击事件
$("#btn").mouseenter(function(){
$(this).css("backgroundColor","red");
});
$("#btn").mouseleave(function(){
$(this).css("backgroundColor","green");
});
$("#btn").click(function(){
alert("love wins");
});
//第二种写法
$("#btn").mouseenter(function(){
$(this).css("backgroundColor","red");
}).mouseleave(function(){
$(this).css("backgroundColor","green");
}).click(function(){
alert("love wins");
});
//第三种写法:bind方法绑定事件
$("#btn").bind("click",function(){
alert("love wins");
});
$("#btn").bind("mouseenter",function(){
$(this).css("backgroundColor","red");
});
$("#btn").bind("mouseleave",function(){
$(this).css("backgroundColor","green");
});
//第四种
$("#btn").bind({"click":function() {
alert("love wins");
},"mouseenter":function() {
$(this).css("backgroundColor", "red");
},"mouseleave":function(){
$(this).css("backgroundColor","green");
}});
});
</script>
......
<input type="button" value="显示效果" id="btn" />
为元素绑定多个相同事件的方式及注意问题
$(function(){
//为按钮绑定多个相同事件
$("#btn").click(function(){
console.log("love wins");
}).click(function(){
console.log("love matters");
}).click(function(){
console.log("love, no boundary");
});
});
$("#btn").bind("click",function(){
console.log("love wins");
}).bind("click",function(){
console.log("love matters");
});
bind方法绑定多个相同事件的时候,如果使用的是键值对的方式,只能执行最后一个。
为元素绑定事件的三种方式
对象.事件名字(事件处理函数);——$("#btn").click(function(){});
对象.bind("事件名字",事件处理函数);——$("#btn").bind("click",function(){});
//上两种只能为存在的元素绑定事件,后添加的元素没有事件
//下两种可以为存在的元素绑定事件,后添加的元素也有事件
父级对象.delegate("子级元素","事件名字",事件处理函数);——>$("#dv").delegate("p","click",function(){});
delegate方法是调用的on的方法,以后直接用on就可以
<style>
div{
width:300px;
height:200px;
background-color: green;
}
p{
width:100px;
height:30px;
background-color: red;
cursor:pointer;
}
</style>
<script src="jquery-1.12.1.js"></script>
<script>
$(function(){
//点击按钮为div绑定事件
//此时on和delegate作用一样,但参数的顺序不一样
$("#btn1").click(function(){
$("<p>这是一个p</p>").appendTo($("#dv"));
//和delegate一样都是为子元素绑定事件
$("#dv").on("click","p",function(){
alert("p被点击了");
});
});
$("$btn2").click(function(){
$("<p>这是2p</p>").appendTo($("#dv"));
});
});
</script>
......
<input type="button" value="绑定事件" id="btn1"/>
<input type="button" value="绑定事件" id="btn2"/>
<div id="dv"></div>