给同一元素绑定多个事件

给同一元素绑定多个事件

$(".aa").on("click",function(){
alert(1)
}).on("mousemove",function(){
console.log(1);
});
$(".aa").on({click:function(){
alert(1)
},mousemove:function(){
console.log(2);
}})

如果需要传参数,除定义全局变量,在方法中直接使用全局变量外,还可使用以下方法

$(".aa").on("click",{val:a},a1).on("mousemove",{val:b},a2);
function a1(e){
alert(e.data.val)
}
function a2(e){
console.log(e.data.val)
}

通过delegate给同一元素绑定多个事件

$("body").delegate(
".msg-layer",{
mousedown: function (e) {
var el = $(".msg-layer");
var os = el.offset(),
dx = e.pageX - os.left, dy = e.pageY - os.top;
$(document).on('mousemove.drag', function (e) {
el.offset({top: e.pageY - dy, left: e.pageX - dx});
});
},
mouseup: function (e) {
$(document).off('mousemove.drag');
}
}
);
$("body").delegate(
".msg-layer","mousedown mouseup",function(e){
if(e.type == "mousedown"){
var el = $(".msg-layer");
var os = el.offset(),
dx = e.pageX - os.left, dy = e.pageY - os.top;
$(document).on('mousemove.drag', function (e) {
el.offset({top: e.pageY - dy, left: e.pageX - dx});
});
}else if(e.type == "mouseup"){
$(document).off('mousemove.drag');
}
}
);
05-11 11:09