gpt4 book ai didi

javascript - 在javascript中对数据进行排序

转载 作者:行者123 更新时间:2023-11-30 14:04:40 26 4
gpt4 key购买 nike

我有一个问题 - 我在我的 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>

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

创建了一个新 View 而不是更新我的实际 View ,如何解决?

提前感谢您的回答!

最佳答案

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

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

Modified Plunker

关于javascript - 在javascript中对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55672626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com