Jquery empty() remove() detach() 方法的区别
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div id="box1">box1</div> <button id="btn1">btn1</button> <div id="box2">box2</div> <button id="btn2">btn2</button> <script src="http://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.3.min.js"></script> <script> $(‘#box1‘).click(function() { console.log(‘box1‘) }) $(‘#box2‘).click(function() { console.log(‘box2‘) }) $(‘#box1‘).data(‘key1‘, ‘value1‘) $(‘#box2‘).data(‘key2‘, ‘value2‘) var $box1 var $box2 $(‘#btn1‘).click(function() { console.log($(‘#box1‘).data(‘key1‘)) if ($box1) { $(‘#btn1‘).before($box1) $box1 = null } else { $box1 = $(‘#box1‘).detach() } }) $(‘#btn2‘).click(function() { console.log($(‘#box2‘).data(‘key2‘)) if ($box2) { $(‘#btn2‘).before($box2) $box2 = null } else { $box2 = $(‘#box2‘).remove() } }) </script> </body> </html>