我有两个html文件index.html和list.html。当我将list.html加载到index.html时,我希望它按照字母顺序自动排序。
index.html:
<button onclick="javascript:showlist()">Show</button>
<div id="content"></div>list.html:
<ul id="myUL">
<li>SUPERMAN</li>
<li>BATMAN</li>
<li>FLASH</li>
<li>ANARKY</li>
</ul>js:
function showlist(){
$("#content").load("list.html");
sortList();
}
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("myUL");
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) {
// start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("li");
// Loop through all list-items:
for (i = 0; i < (b.length - 1); i++) {
// start by saying there should be no switching:
shouldSwitch = false;
/* check if the next item should
switch place with the current item: */
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
/* if next item is alphabetically
lower than current item, mark as a switch
and break the loop: */
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
/* If a switch has been marked, make the switch
and mark the switch as done: */
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}发布于 2021-06-17 23:52:16
缺少的部分是满载处理程序。否则,您可能会在内容加载之前调用sortList()。否则,您的功能就能工作了。
$("#content").load("list.html", function() {
console.log("Loaded");
sortList();
})发布于 2021-06-17 23:49:32
在加载列表之前,不能对其排序
您需要在div上使用事件加载。
将其编码如下:
function showlist() {
$('#content').load('list.html');
}
const contentDiv = document.querySelector('#content')
contentDiv.onload =_=>
{
const
list = contentDiv.querySelector(`ul`)
, arrLI = [...list.querySelectorAll('li')]
.map(li=>({key:li.textContent.toLowerCase(),li}))
.sort((a,b)=>a.key.localeCompare(b.key))
arrLI.forEach(el=>list.appendChild(el.li) )
}下面是演示排序工作方式的代码:
sortList('#content')
function sortList( parentDiv )
{
const
list = document.querySelector(`${parentDiv} > ul`)
, arrLI = [...list.querySelectorAll('li')]
.map(li=>({key:li.textContent.toLowerCase(),li}))
.sort((a,b)=>a.key.localeCompare(b.key))
arrLI.forEach(el=>list.appendChild(el.li) )
}<div id="content">
<ul>
<li>SUPERMAN</li>
<li>BATMAN</li>
<li>FLASH</li>
<li>ANARKY</li>
</ul>
</div>
https://stackoverflow.com/questions/68027564
复制相似问题