DIV CSS 佈局教程網

jQuery clone(true) 的事件複製 Bug 追蹤與解法
編輯:JQuery特效代碼     

先看事件是怎麼存的

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;
});

Bug 再現

<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 上。

Bug 的來源

// 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

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved