为了账号安全,请及时绑定邮箱和手机立即绑定

重新排列 HTML 表格

重新排列 HTML 表格

慕尼黑8549860 2024-01-03 17:29:16
我有一个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})  
查看完整描述

2 回答

?
斯蒂芬大帝

TA贡献1827条经验 获得超8个赞

这是一种方法,如何在单击按钮后每 5 秒对数组进行一次洗牌,如果多次单击它,它将始终取消先前的超时实例


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

  }

]




const arrRandomIndex = []

const newArr = [];


while (arrRandomIndex.length !== data.length) {

  const randomNum = Math.floor(Math.random() * data.length);

  if (!arrRandomIndex.includes(randomNum)) {

    arrRandomIndex.push(randomNum);

  }

}


for (let i = 0; i < data.length; i++) {

  newArr[i] = data[arrRandomIndex[i]];

}


let timeId;


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

  clearTimeout(timeId);

  timeId = setTimeout(_ => console.log('Random array', newArr), 5000)

})

<button id="alter">

AlTER

</button>


查看完整回答
反对 回复 2024-01-03
?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

给定的rows是一个节点列表tr


function randomise() {

    for (const row of rows) {

        const table = row.parentElement;

        table.insertBefore(

            row,

            table.children[Math.floor(Math.random() * table.children.length)]

        );

    }

}


alter.addEventListener("click", () => {

    randomise();

    setInterval(function () {

        randomise();

    }, 5000);

});


查看完整回答
反对 回复 2024-01-03
  • 2 回答
  • 0 关注
  • 55 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信