我认为您可以这样做:通过克隆 div 并将数据(“事件”)保存在对象中来存储 div 的事件。之后您迭代对象并绑定事件。您必须克隆,因为当您取消绑定事件时,原始数据(“事件”)被删除。(希望我明白您在寻找什么)
<div id='my'>my</div>
var my = $('#my');
my.click(function(){
alert('my');
});
my.hover(function(){
$(this).css('color', 'red');
});
my.click(function(){
alert('you');
});
var ev =my.clone(true).data('events');
my.unbind();
for (var e in ev){
//you have to iterate on the property since is an array with all the handlers for the same event)
for (i= 0; i < ev[e].length; i++){
my.bind(e, ev[e][i]);
}
}
小提琴http://jsfiddle.net/pXAXW/
编辑 - 要在 1.5.2 中进行这项工作,您只需要更改附加事件的方式,因为它们的保存方式不同:
$(document).ready(function(){
var theDiv = $("#thediv");
theDiv.click(function(){
$(this).css("border-color", "blue");
alert("Click!");
});
theDiv.click(function(){
$(this).css("border-color", "blue");
alert("clack!");
});
var theEvents = theDiv.clone(true).data("events");
// Unbind events from the target div
theDiv.unbind("click");
// Put the saved events back on the target div
for (var e in theEvents){
// must iterate through since it's an array full of event handlers
for ( i=0; i<theEvents[e].length; i++ ){
theDiv.bind(e, theEvents[e][i].handler);
}
}
});
在这里小提琴:(与 Katiek 相同)http://jsfiddle.net/nicolapeluchetti/CruMx/2/(如果您不完全单击 div,该事件会触发两次!)我还更新了我的小提琴以使用 jquery 1.5 .2 http://jsfiddle.net/pXAXW/1/ )