JQuery DOM clone(true),對於克隆對象事件觸發后,處理函數中this指代克隆對象


<!doctype html>
<html ng-app>
    <head>
        <script src="./jquery.js"></script>
    </head>
    <body>
        <div id="template">hello</div>
        <script type="text/javascript">
            $("#template").click(function(){alert("hello id="+$(this).attr("id"))})

            var templateClone = $("#template").clone(true);

            templateClone.attr("id", templateClone.attr("id")+"_"+1);
            
            templateClone.appendTo("body");
        </script>
    </body>
</html>

 如上實驗, 第二行文字點擊, 顯示第二個id。

 

具體原因是, 事件被克隆, 但是事件處理函數沒有被執行, 事件處理函數在clone對象的事件處理后才執行, 其中this為,觸發此函數執行的對象。

見zhangxinxu解釋:

http://www.zhangxinxu.com/wordpress/2012/04/js-dom%e8%87%aa%e5%ae%9a%e4%b9%89%e4%ba%8b%e4%bb%b6/

ar $ = function(el) {
    return new _$(el);    
};
var _$ = function(el) {
    this.el = el;
};
_$.prototype = {
    constructor: this,
    addEvent: function() {
        // ...
    },
    fireEvent: function() {
        // ...
    },
    removeEvent: function() {
        // ...
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM