我使用循环到HTML DIV获取一些数据。可以有更多的数据。数据显示如下代码.DIV有两个类(test one
和test two
)
如何显示所有"测试一个"首先是数据,然后是"测试两个"数据。如何使用 javascript
或 Jquery
执行此操作?
HTML
<div class="container">
<div class="test one">1</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test two">2</div>
</div>
答案 0 :(得分:5)
这可以使用flexbox的order
属性来实现:
.container {
display: flex;
flex-direction: column;
}
.test.two {
order: 2;
}
<div class="container">
<div class="test one">1</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test two">2</div>
</div>
答案 1 :(得分:2)
使用可以通过克隆容器完成的jQuery库然后循环遍历克隆实例并先获取.one
元素,然后获取.two
元素,并在使用它清除后将它们附加到原始容器$('.container').html('');
,请查看下面的工作代码段。
希望这会对你有所帮助。
var container = $('.container').clone();
$('.container').html('');
container.find('.one').each(function() {
$('.container').append($(this)[0].outerHTML);
})
container.find('.two').each(function() {
$('.container').append($(this)[0].outerHTML);
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="test one">1</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test two">2</div>
</div>
&#13;
答案 2 :(得分:2)
jQuery(document).ready(function($) {
var items = $('.container .test').get();
console.log(items);
items.sort(function(a,b){
var keyA = $(a).text();
var keyB = $(b).text();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
var container = $('.container');
$.each(items, function(i, div){
container.append(div);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="test one">1</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test two">2</div>
</div>
答案 3 :(得分:1)
您可以在包含元素的数组上使用简单的Array.prototype.sort()
,并替换.container
元素的innerhtml。
var elements = $('.container').children();
elements.sort(function(a,b){
return a.className > b.className;
});
$('.container').html(elements);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="test one">1</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test one">1</div>
<div class="test two">2</div>
<div class="test two">2</div>
</div>