4 回答
TA贡献1831条经验 获得超10个赞
您可以使用 flex 非常轻松地更改 HTML 元素的顺序。
let changeOrder = () => {
const stackOrder = [{name: "A", order: 3}, {name: "B", order: 1}, {name: "C", order: 2}];
for (let item of stackOrder) {
$('#' + item.name)[0].style.order = item.order;
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container" style="display: flex; flex-direction: column;">
<div id="A"> Form elements for A</div>
<div id="B"> Elements that go to B</div>
<div id="C"> CCC ccAadas</div>
</div>
<input type="button" value="ascending" onclick="changeOrder()">
TA贡献1859条经验 获得超6个赞
您可以使用lodash
库来排序结果,请考虑以下内容。假设list
您从数据库返回的内容,请使用该_.orderBy
函数并选择您想要排序的字段
const _ = require('lodash')
....
const list = [{name: "A", order: 3}, {name: "C", order: 2}, {name: "B", order: 1}]
const sorted = _.orderBy(list, 'name')
TA贡献1111条经验 获得超0个赞
首先,您可以根据顺序对数组进行排序
order.sort((a, b) => {
return a.order - b.order;
});
完成后,循环遍历数组,在每次迭代期间创建一个 div 并将其附加到主容器。
for (let i = 0; i < order.length; i++) {
let div = document.createElement("div");
div.id = order[i].name;
div.innerText = `This is ${order[i].name} div`; // for displaying test purposes
document.getElementById('main').appendChild(div);
}
完整示例在这里: https: //jsfiddle.net/bg7sh2rx/
TA贡献1887条经验 获得超5个赞
您可以在 Angular JS 中使用具有 ng-repeat 功能的自定义排序。下面是工作示例。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-repeat="x in records | orderBY:'order'">{{x.name}}</h1>
<script>
var app = angular.module("myApp", []);
app.filter('orderBY', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
array.push(input[objectKey]);
}
array.sort(function(a, b){
a = parseInt(a[attribute]);
b = parseInt(b[attribute]);
return a - b;
});
return array;
}
});
app.controller("myCtrl", function($scope) {
$scope.records =[{name: "A", order: 3}, {name: "B", order: 1}, {name: "C", order: 2}]
});
</script>
</body>
</html>
- 4 回答
- 0 关注
- 117 浏览
添加回答
举报