题解 | #列表内容排序再渲染#
列表内容排序再渲染
https://www.nowcoder.com/practice/2dffcb354a484995894655a5547b0b49
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <ul id="myList"> <li id="item1">项目 1</li> <li id="item3">项目 3</li> <li id="item2">项目 2</li> <li id="item4">项目 4</li> </ul> <script> function sortAndReturnTextContent() { const items = Array.from(document.getElementById('myList').children); // 在此补全代码 for (let j = 0;j < items.length; j++){ for (let i = 0;i < items.length- j - 1; i++){ if( items[i].id > items[i+1].id ){ let temp = items[i]; items[i] = items[i+1]; items[i+1] = temp; } } } for (const item of items) { document.getElementById('myList').appendChild(item); } } sortAndReturnTextContent() </script> </body> </html>