主页 个人前端笔记 2个div交换内容不影响事件,易出错的问题分析
admin
发表于2012-11-11 18:58:17    只看楼主 楼主
头衔:  精益求精
注册时间: 2012-10-07
用户组: 日常管理组
发帖数:  502
金币数:  187
短消息
<div id="tip1" style="width:100px;height:100px;border:1px solid red">
   <div id="sp" style="height:50px;height:50px;border:1px solid blue"></div>
</div>
<div id="tip2" style="width:100px;height:100px;border:1px solid green">
   <div id="sp2" style="height:50px;height:50px;border:1px solid blue"></div>
</div>

如果要将tip1的内容移到tip2中

方法1

var tmp=$("tip1").innerHTML;
$("tip1").innerHTML=$("tip2").innerHTML;
$("tip2").innerHTML=tmp;

这种方法没错,但是如果sp,sp2节点上注册了事件,按第一种方法处理,事件会失效。

方法2

 <script type="text/javascript">
        var sp = document.getElementById("sp");
        var sp2 = document.getElementById("sp2");
        var tip1 = document.getElementById("tip1");
        var tip2 = document.getElementById("tip2");
        sp.onclick = function (e) {
            var e = e || window.event;
            if (!document.all) e.stopPropagation()
            else window.event.cancelBubble = true
            alert('sp1');
        };
         sp2.onclick = function (e) {
            var e = e || window.event;
            if (!document.all) e.stopPropagation()
            else window.event.cancelBubble = true
            alert('sp2');
        };
        tip1.onclick = function () {
            tip2.appendChild(sp);
            tip1.appendChild(sp2);
        };
 </script>

这种处理方式可以保留事件处理,但是点击只能交换一次,而innerHTML是可以点击来回交换其中内容。
第二种方法的易错点在于会使用removeChild来删除节点,因为在tip1中加入节点对象sp2之后,该sp2节点对象就不存在tip2中了。
引用回复  把握生命里的每一分钟,没有人能随随便便成功~^_^

回复人
回复内容

Powered BY YouYaX
个人自主开发论坛,从2010年10月份开发至今!

操作管理