我有以下div布局:
<div class="container">
<div class="entry">
<div class="title">World</div>
<div class="description">text1</div>
</div>
<div class="entry">
<div class="title">hello</div>
<div class="description">text2</div>
</div>
<div class="entry">
<div class="title">Lorem</div>
<div class="description">text3</div>
</div>
</div>
我想按子标题div的内容按字母顺序对条目div进行排序.
到目前为止我尝试过的
这将按字母顺序排序:
var alphabeticallyOrderedDivs = $('.title').sort(function(a, b) {
return String.prototype.localeCompare.call($(a).text().toLowerCase(), $(b).text().toLowerCase());
});
var container = $(".container");
container.detach().empty().append(alphabeticallyOrderedDivs);
$('body').append(container);
但是它将删除描述div.尝试jsFiddle demo.
如何在不剥离任何内容的情况下按字母顺序对div排序?
解决方法:
您的逻辑是正确的,但是问题是您正在对.title元素进行排序.相反,您需要对.entry元素进行排序,然后在当前.entry中找到.title并对它们的文本值进行比较.尝试这个:
var alphabeticallyOrderedDivs = $('.entry').sort(function(a, b) {
var $aTitle = $(a).find('.title'), $bTitle = $(b).find('.title');
return String.prototype.localeCompare.call($aTitle.text().toLowerCase(), $bTitle.text().toLowerCase());
});
var container = $(".container");
container.detach().empty().append(alphabeticallyOrderedDivs);
$('body').append(container);
.entry {
border: 1px solid #CCC;
padding: 5px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="container">
<div class="entry">
<div class="title">World</div>
<div class="description">text1</div>
</div>
<div class="entry">
<div class="title">hello</div>
<div class="description">text2</div>
</div>
<div class="entry">
<div class="title">Lorem</div>
<div class="description">text3</div>
</div>
</div>