$.detach方法_删除dom但保留该dom已绑定的事件

五级会员 站长
发表于JQuery分类
方法说明:

从DOM中移除匹配的元素集但保留该DOM已绑定的事件。.detach()方法与.remove()方法相同,只是.detach()保留与被删除元素相关的所有jQuery数据。当删除的元素稍后要重新插入DOM时,此方法非常有用。


基本用法:

.detach( [selector ] )


应用举例:

<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>detach demo</title> <style> p { background: yellow; margin: 6px 0; } p.off { background: black; } </style> <script src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js"></script> </head> <body> <p>Hello</p> how are <p>you?</p> <button>Attach/detach paragraphs</button> <script> $( "p" ).click(function() { $( this ).toggleClass( "off" ); }); var p; $( "button" ).click(function() { if ( p ) { p.appendTo( "body" ); p = null; } else { p = $( "p" ).detach(); } }); </script> </body> </html>


登录 分类