$(".test1").before($('h2')) 新增內(nèi)容為H2的時候,為什么會將初始的H2刪除,點“after”按鈕后又會將“before”按鈕新增的H2刪除
<!DOCTYPE html>
<html>
<head>
? ? <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
? ? <title></title>
? ? <script src="http://idcbgp.cn/static/lib/jquery/1.9.1/jquery.js"></script>
? ? <style>
? ? .aaron{? ? ? ? border: 1px solid red;? ? }
? ? </style>
</head><body>
? ? <h2>通過before與after添加元素</h2>
? ? <button id="bt1">點擊通過jQuery的before添加元素</button>
? ? <button id="bt2">點擊通過jQuery的after添加元素</button>
? ? <div class="aaron">
? ? ? ? <p class="test1">測試before</p>
? ? </div>
? ? <div class="aaron">
? ? ? ? <p class="test2">測試after</p>
? ? </div>
? ? <script type="text/javascript">
? ? $("#bt1").on('click', function() {
? ? ? ? //在匹配test1元素集合中的每個元素前面插入p元素
? ? ? ? $(".test1").before($('h2'))
? ? })
? ? </script>
? ? <script type="text/javascript">
? ? $("#bt2").on('click', function() {
? ? ? ? //在匹配test1元素集合中的每個元素后面插入p元素
? ? ? ? $(".test2").after($("h2"))
? ? })
? ? </script>
</body>
2019-08-06
如果你使用頁面已有的dom的話,就只相當(dāng)于搬運,而不是生成新的節(jié)點
2019-02-21
?$(".test1").before($('h2'))和?$(".test2").after($("h2"))中的$('h2')改成$('<h2>nihao</h2>')就好了