detach()
<html>
<head>
? ? <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
? ? <script src="http://www.xianlaiwan.cn/static/lib/jquery/1.9.1/jquery.js"></script>
? ? <style type="text/css">
? ? p {
? ? ? ? color: red;
? ? }
? ? </style>
</head>
<body>
? ? <p>P元素1,默認給綁定一個點擊事件</p>
? ? <p>P元素2,默認給綁定一個點擊事件</p>
? ? <button id="bt1">點擊刪除 p 元素</button>
? ? <button id="bt2">點擊移動 p 元素</button>
? ? <script type="text/javascript">
? ? $('p').click(function(e) {
? ? ? ? alert(e.target.innerHTML)
? ? })
? ? var p;
? ? $("#bt1").click(function() {
? ? ? ? if (!$("p").length) return; //去重
? ? ? ? p = $("p").detach()
? ? });
? ? $("#bt2").click(function() {
? ? ? ? //把p元素在添加到頁面中
? ? ? ? //事件還是存在
? ? ? ? $("body").append(p);
? ? });
? ? </script>
</body>
</html>
2018-03-14
? $("#bt1").click(function() {
? ? ? ? if (!$("p").length) return; //去重
? ? ? ? p = $("p").detach()
? ? });
如果p的length為0,也就是if條件(!$("p").length)為1,即為真,返回,就不進行下一條語句了。
如果p的length為1,也就是if條件(!$("p").length)為0,即為假,就不return了,才進行下一條語句,保留p的數據,然后刪除p(我認為可以理解為邏輯刪除)
哪位親如果覺得不對請指正