开发者

Emulate jQuery .detach() in older version?

开发者 https://www.devze.com 2023-03-27 23:08 出处:网络
I\'m using jQuery 1.3.2 and currently I\'m not in a position where I can hope for an upgrade. Consider this code that works in 1.4.2:

I'm using jQuery 1.3.2 and currently I'm not in a position where I can hope for an upgrade. Consider this code that works in 1.4.2:

var some_elem = $('#some_element');
var other_elem = $('#other_element');
some_elem.detach();
other_elem.replaceWith(some_elem);

How should开发者_开发问答 I rewrite this code to make it work in jQuery 1.3.2? It doesn't implement the .detach() method.


detach [source] is calling remove [source] but sets a special flag to not delete all the data jQuery is using internally and was attached via data().

Aprat from clearing the data, remove is only doing the following to remove the element:

elem.parentNode.removeChild( elem );

You could create your own plugin:

(function($) {
    if(!$.fn.detach) {
        $.fn.detach = function() {
            return this.each(function() {
                if(this.parentNode) {
                    this.parentNode.removeChild( this );
                }
            });
       };
    }
}(jQuery));


From the documentation for .detach():

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

"All jQuery data" means all bound events and .data() items.

If you don't care about this, use .remove(), which has existed in jQuery since version 1.0.

0

精彩评论

暂无评论...
验证码 换一张
取 消