【问题标题】:Sort data in javascript在javascript中对数据进行排序
【发布时间】:2019-04-14 06:40:55
【问题描述】:

我有问题 - 我在我的 html data 中显示来自 javascript,点击后我必须对其进行排序。这是我的代码:

const data = [
  {
    "id": 2,
    "title": "ASD",
    "src": "https://cloudfour.com/examples/img-currentsrc/images/kitten-small.png"
  },
  {
    "id": 1,
    "title": "FGH",
    "src": "https://cloudfour.com/examples/img-currentsrc/images/kitten-small.png"
  }
]
const info_container = document.querySelector('.info-container')

const sort = () => {
  data.sort((a, b) => parseFloat(a.id) - parseFloat(b.id))

  fetchData()
}

const fetchData = () => {
  data.forEach((item, index) => {
  const img = document.createElement("img");
  const title = document.createElement('h3')

  const node = document.createTextNode(item.src);
  const node_title = document.createTextNode(item.title)

  title.appendChild(node_title)
  img.src = item.src

  info_container.appendChild(title)
  info_container.appendChild(img);

})
}
window.onload = function() {
  fetchData()
}

HTML:

<div><button onclick="sort()">sort</button></div>
  <div class="info-container">    
</div>

plunker:http://plnkr.co/edit/Yjn4jaLN45pYJHFZBZLn?p=preview

没有更新我的实际视图,而是创建了一个新视图,如何解决?

提前感谢您的回答!

【问题讨论】:

  • 你不会在任何地方打电话给sort ...所以,这就是一件事
  • 查看 plunker,我在 html 中调用 sort onclick 按钮
  • 我为什么要寻找其他地方?如果你确实调用了排序,那么它当然会添加到数据中......你所做的就是 appendChild
  • 我已经编辑了我的问题
  • 删除旧内容再添加排序后的内容

标签: javascript html arrays object


【解决方案1】:

每次调用fetchData时都需要重置info_container的内容:

const fetchData = () => {
  info_container.innerHTML = "";
  //Rest of the code
}

Modified Plunker

【讨论】:

    【解决方案2】:
    1. 奇怪的是,您没有在每次点击事件时释放您的info_container 孩子数量增加。你想用一个新的内容替换你的info_container 内容,所以你的新内容结构乍一看并不重要,你应该编写一个完成这项工作的函数,检查你至少可以用一个新的字符串替换一个字符串.有了@jack Bashford 的回复,您就有了解决方案

    2. 第二个措辞可以在代码中有所帮助,只是稍微注意一下,您的 fetchData 根本没有获取任何内容

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 2014-05-22
      • 2022-11-23
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多