Stay Hungry,Stay Foolish!

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() {
        // ...
    }
}
复制代码
posted @   lightsong  阅读(4101)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
千山鸟飞绝,万径人踪灭
点击右上角即可分享
微信分享提示