按列表中的顺序对 html DOM 元素进行排序

如何<div>根据从数据库获取的顺序更改其中的顺序和元素?


假设这是我的 HTML:


<div id="container">

    <div id="A"> Form elements for A</div>

    <div id="B"> Elements that go to B</div>

    <div id="C"> CCC ccAadas</div>

</div>

这是按顺序排列的列表:


$scope.order = [{name: "A", order: 3}, {name: "B", order: 1}, {name: "C", order: 2}]

我该如何显示 div B,然后显示 div C,最后显示 div A?


慕妹3242003
浏览 126回答 4
4回答

慕哥6287543

您可以使用 flex 非常轻松地更改 HTML 元素的顺序。let changeOrder = () => {&nbsp; &nbsp;const stackOrder = [{name: "A", order: 3}, {name: "B", order: 1}, {name: "C", order: 2}];&nbsp; &nbsp; &nbsp; &nbsp;for (let item of stackOrder) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#' + item.name)[0].style.order = item.order;&nbsp; &nbsp; &nbsp; &nbsp;}};&nbsp; &nbsp;&nbsp;<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>&nbsp; &nbsp; <div id="container" style="display: flex; flex-direction: column;">&nbsp; &nbsp; &nbsp; &nbsp; <div id="A"> Form elements for A</div>&nbsp; &nbsp; &nbsp; &nbsp; <div id="B"> Elements that go to B</div>&nbsp; &nbsp; &nbsp; &nbsp; <div id="C"> CCC ccAadas</div></div><input type="button" value="ascending" onclick="changeOrder()">

BIG阳

您可以使用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')

catspeake

首先,您可以根据顺序对数组进行排序order.sort((a, b) => {&nbsp; &nbsp; return a.order - b.order;});完成后,循环遍历数组,在每次迭代期间创建一个 div 并将其附加到主容器。for (let i = 0; i < order.length; i++) {&nbsp; let div = document.createElement("div");&nbsp; div.id = order[i].name;&nbsp; div.innerText = `This is ${order[i].name} div`; // for displaying test purposes&nbsp; document.getElementById('main').appendChild(div);}完整示例在这里: https:&nbsp;//jsfiddle.net/bg7sh2rx/

慕工程0101907

您可以在 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(){&nbsp;return function(input, attribute) {&nbsp; &nbsp; if (!angular.isObject(input)) return input;&nbsp; &nbsp; var array = [];&nbsp; &nbsp; for(var objectKey in input) {&nbsp; &nbsp; &nbsp; &nbsp; array.push(input[objectKey]);&nbsp; &nbsp; }&nbsp; &nbsp; array.sort(function(a, b){&nbsp; &nbsp; &nbsp; &nbsp; a = parseInt(a[attribute]);&nbsp; &nbsp; &nbsp; &nbsp; b = parseInt(b[attribute]);&nbsp; &nbsp; &nbsp; &nbsp; return a - b;&nbsp; &nbsp; });&nbsp; &nbsp; return array;&nbsp;}});app.controller("myCtrl", function($scope) {&nbsp; $scope.records =[{name: "A", order: 3}, {name: "B", order: 1}, {name: "C", order: 2}]});</script></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5