如何使用jQuery在HTML中按字母顺序对列表进行排序?

3
我有两个html文件index.htmllist.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;
    }
  }
}

我将其转换为代码片段,因为它已经可以工作,所以没有发布编辑。问题是什么?这已经可以正常运行了。 - Samathingamajig
已经有答案了。但是问题来自于两个不同的文件。如果每次从我的索引中加载列表时都这样做,它就不会按字母顺序排序。你需要创建一个 sortList() 按钮来进行排序(A-Z)。 - ProgrammerPickleRick
3个回答

3
缺少的部分是onload处理程序。没有它,你可能在内容加载之前调用了sortList()。否则你的功能是有效的。
$("#content").load("list.html", function() {
    console.log("Loaded");
    sortList();
})

2

当列表加载完成之前,无法对其进行排序
您需要在div元素上使用load事件
代码如下:

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>


问题是我的列表是从其他文件中故意获取的,我只需要从我的索引调用它并将其显示到特定的div中。 - ProgrammerPickleRick
@Asklepiades 这只是为了展示它的工作原理。您可以在您的 load 函数中使用 sortList('#content') - Mister Jojo
@Asklepiades 我在我的回答中添加了一种使用它的方法。 - Mister Jojo

0
正如最佳答案所提到的,您必须在.load()回调中运行排序代码。但我还是要再次回答,因为您的排序代码有些混乱。您可以使用.append(), .detach(), 和.sort() 来编写更干净的代码。
$('#content').load('list.html', function() {
  $('ul').append($('li').detach().sort((a, b) => a.textContent > b.textContent));
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接