jQuery 綁定事件時,所有處理器都存在 $.cache 裡,可以用 data('events') 反覆取出:
var $div = $('div.demo'), data = $div.data();
var events = data.events; // 取得所有綁定的事件
var windowEvents = $(window).data('__events__'); // window 物件綁定的事件比較特殊
需要時也可以檢查某個處理函式是否已綁定:
var clickHandler = function () { console.log('click test'); };
$div.click(clickHandler);
events.click.some(function (ev) {
return ev.handler === clickHandler;
});
<script type="text/javascript">
Array.prototype.xyzz = function (arg) { console.log(1, this, arg); };
Array.prototype.xyzzz = function (arg) { console.log(2, this, arg); };
$(function () {
$('button').click(function () {
$('div.demo').clone(true).appendTo('body');
});
$('div.demo').click(function () {
console.log('click..');
});
});
</script>
只要你擴充了 Array.prototype,再呼叫 clone(true),就會看到多餘的方法被當成事件處理器綁到 DOM 上。
// event.js, jQuery.event.add:
handlers = events[type] = {}; // jQuery 1.4.1
handlers = events[type] = []; // jQuery 1.4.2+
// manipulation.js, jQuery.clone → cloneCopyEvent():
for (var type in events) {
for (var handler in events[type]) {
jQuery.event.add(this, type, events[type][handler], events[type][handler].data);
}
}
1.4.2 之後 events[type] 改成了陣列,而 for...in 會把陣列原型鏈上擴充的所有方法都遍歷出來,於是這些方法就被當成事件處理器綁到複製出來的節點上了。
三個方向:不要擴充陣列原型、避免使用 clone(true)、或者用 hasOwnProperty 過濾。最乾淨的做法是把迴圈改成 each:
var self = this;
for (var type in events) {
jQuery.each(events[type], function (idx, evt) {
jQuery.event.add(self, type, evt.handler, evt.data);
});
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Clone Bug</title>
<style type="text/css">
.demo { margin: 1em; background: #07a; height: 10em; width: 10em; }
</style>
</head>
<body>
<button>doClone</button>
<a href="https://www.poluoluo.com">返回</a>
<div class="demo">click me</div>
<script src="https://demo.jb51.net/jslib/jquery/jquery-1.4.4.js"></script>
<script type="text/javascript">
Array.prototype.xyzz = function (arg) { console.log(1, this, arg); };
Array.prototype.xyzzz = function (arg) { console.log(2, this, arg); };
$(function () {
$('button').click(function () {
$('div.demo').clone(true).appendTo('body');
});
$('div.demo').click(function () {
console.log('click..');
});
});
/* 對照用: manipulation.js 的 cloneCopyEvent 大約在第 372 行
for (var type in events) {
for (var handler in events[type]) { console.log(handler); }
}
console.log($.isArray(events['click']));
*/
</script>
</body>
</html>
線上範例:/js/jquery_clone_bug/jQuery_clone_bug_demo.htm