首先显示初始状态:
<body>
<div class="parent">
<div class="child">0</div>
<div class="child">1</div>
<div class="child">2</div>
</div>
<script src="common/jquery/jquery-3.3.1.js"></script>
<script>
$(function(){
var parent = $('.parent') //获取父元素
var childs = parent.children(); //获取所有的子元素
})
</script>
</body>
以上显示为:
正常使用append()向父元素内追加第一个子元素:
$(function(){
var parent = $('.parent')
var childs = parent.children();
parent.append(childs.eq(0)); //使用append()向父元素内追加第一个子元素
})
显示结果为:第一个子元素被拿走后追加到了父元素的末尾。
但是我们要实现我们理想中的追加效果,需要这样的写法:
$(function(){
var parent = $('.parent')
var childs = parent.children();
var childsHTML = parent.html(); //获取包含所有的子元素的字符串
var rule = /\>\s*\</g; //匹配到所有的 “ >< ” 或 “ > <” 字符串
childsHTML = childsHTML.replace(rule, '>,<').split(','); //将所有的子元素分割成数组
parent.append(childsHTML[0]); //将选中的元素追加到父元素的最后一位
})
显示结果为: