javascript - 替换html元素,不解绑事件,应该怎么做?
本文介绍了javascript - 替换html元素,不解绑事件,应该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
> 'click .enable': function(e, value, row, index) {
> var that = $(this);
>
> // console.log(row);
> // console.log($(that).closest("tr").find(".stop"));
> $(that).closest("tr").find(".stop").replaceWith('<span class="label label-success start">已启用</span>');
> $(that).replaceWith('<a class = "disable btn blue btn-xs blue-stripe" href="javascript:void(0)">停用</a>');
> console.log($(that));
>
>
>
> },
> 'click .disable': function(e, value, row, index) {
> var that = $(this);
>
> $(that).closest("tr").find(".start").replaceWith('<span class="label label-primary stop">已停用</span>');
> $(that).replaceWith('<a class = "enable btn green btn-xs green-stripe" href="javascript:void(0)">启用</a>');
>
> }
目前用了relaceWith方法替换所选择的元素,但是事件也销毁了,请问大家有什么好的办法。
解决方案
代码没看太懂,如果是绑定事件的DOM结构被拿掉了的话,可以绑到它的父级做事件代理。
另外,事件处理里的this已经被$包装过也缓存过了,就不要再次包装了吧。
这篇关于javascript - 替换html元素,不解绑事件,应该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文