猿问

重新排列 HTML 表格

我有一个JSON这样的数据:


var data = [

    {"city":"seattle", "state":"WA", "population":652405, "land_area":83.9},

    {"city":"new york", "state":"NY", "population":8405837, "land_area":302.6},

    {"city":"boston", "state":"MA", "population":645966, "land_area":48.3},

    {"city":"kansas city", "state":"MO", "population":467007, "land_area":315}

  ]

我已将此JSON数据添加到我的HTML表中。5 seconds现在,每次单击按钮时如何随机排列这些数据?


alter.addEventListener('click', function() {

    //code goes here

})  


慕尼黑8549860
浏览 134回答 2
2回答

斯蒂芬大帝

这是一种方法,如何在单击按钮后每 5 秒对数组进行一次洗牌,如果多次单击它,它将始终取消先前的超时实例var data = [{&nbsp; &nbsp; "city": "seattle",&nbsp; &nbsp; "state": "WA",&nbsp; &nbsp; "population": 652405,&nbsp; &nbsp; "land_area": 83.9&nbsp; },&nbsp; {&nbsp; &nbsp; "city": "new york",&nbsp; &nbsp; "state": "NY",&nbsp; &nbsp; "population": 8405837,&nbsp; &nbsp; "land_area": 302.6&nbsp; },&nbsp; {&nbsp; &nbsp; "city": "boston",&nbsp; &nbsp; "state": "MA",&nbsp; &nbsp; "population": 645966,&nbsp; &nbsp; "land_area": 48.3&nbsp; },&nbsp; {&nbsp; &nbsp; "city": "kansas city",&nbsp; &nbsp; "state": "MO",&nbsp; &nbsp; "population": 467007,&nbsp; &nbsp; "land_area": 315&nbsp; }]const arrRandomIndex = []const newArr = [];while (arrRandomIndex.length !== data.length) {&nbsp; const randomNum = Math.floor(Math.random() * data.length);&nbsp; if (!arrRandomIndex.includes(randomNum)) {&nbsp; &nbsp; arrRandomIndex.push(randomNum);&nbsp; }}for (let i = 0; i < data.length; i++) {&nbsp; newArr[i] = data[arrRandomIndex[i]];}let timeId;document.getElementById('alter').addEventListener('click', function() {&nbsp; clearTimeout(timeId);&nbsp; timeId = setTimeout(_ => console.log('Random array', newArr), 5000)})<button id="alter">AlTER</button>

犯罪嫌疑人X

给定的rows是一个节点列表trfunction randomise() {&nbsp; &nbsp; for (const row of rows) {&nbsp; &nbsp; &nbsp; &nbsp; const table = row.parentElement;&nbsp; &nbsp; &nbsp; &nbsp; table.insertBefore(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; row,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; table.children[Math.floor(Math.random() * table.children.length)]&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}alter.addEventListener("click", () => {&nbsp; &nbsp; randomise();&nbsp; &nbsp; setInterval(function () {&nbsp; &nbsp; &nbsp; &nbsp; randomise();&nbsp; &nbsp; }, 5000);});
随时随地看视频慕课网APP

相关分类

Html5
我要回答