javascript - 我正在尝试根据它们的 id 在 html 中订购 div

标签 javascript html css sorting button

我有一个 div,里面有很多其他的 div,每个里面都有一个按钮。我需要根据它们的 id 对主 div 中的 div 进行排序,但不使用 jQuery 或任何东西,只是干净简单的 JavaScript。我找不到任何方法来做到这一点,所以任何建议将不胜感激。

我去过很多网站,这些网站根据 div 中的文本而不是 id 显示解决方案。

function sortDiv() {
    var mainDiv = document.getElementById("divsGroup");
    var divs = mainDiv.children;
    for (i = 0; i < divs.length(); i++) {
        if //divs[i] is higher in the alphabet than divs[i+1] then  {
            //rearrange the divs 
        };
    };
};

我需要重新排列 div,以便根据其 ID 按字母顺序显示它们。

最佳答案

这是一个解决方案,其中排序位在 id 字符串的简单数组中处理。然后,对于每个 id(已经按字母顺序排列),我们遍历 div 以找到下一个要(重新)插入到 DOM 中的。

document.getElementById("sortBtn").addEventListener("click", sortDivs);

function sortDivs(){
  let mainDiv = document.getElementById("divsGroup"),
      divs = mainDiv.children,
  // `[...divs]` converts `divs` to an Array so we can use the `.map` and `.sort` methods
  divsArray = [...divs];
  // `.map(div => div.id )` makes a new Array of all the `id` strings, and
  // `.sort()` sorts the new Array alphabetically
  idList = divsArray.map(div => div.id).sort();

  //console.log(idList); // logs ["a", "b", "c", "d" ]

  // `idList` and `divsArray` are Arrays, so we can also use 
  //    the `.forEach` method to loop through them
  idList.forEach(id => {
    // As we process each `id` alphabetically, we check each `div`'s id for a match 
    divsArray.forEach(div => {
      if(div.id == id){ // Finds div with matching id
        mainDiv.appendChild(div); // Moves the matching div to bottom of `mainDiv`
      }
    });
  });
}
<div id="divsGroup">
  <div id="d">-d-</div>
  <div id="b">-b-</div>
  <div id="c">-c-</div>
  <div id="a">-a-</div>
</div>
<button id="sortBtn">Sort 'em</button>

注意:此代码可能更短,但对于不熟悉 Array 的 .map.forEach 方法或扩展运算符 (. ..),这个较长的版本可能有助于使事情更清楚。

关于javascript - 我正在尝试根据它们的 id 在 html 中订购 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242737/

相关文章:

javascript - 使用与移动端相同的 API 开发网站

javascript - 在 Meteor 中在客户端和服务器上生成相同的随机数

javascript - 如何解析 wiki 文本表 HTML?

html - 使用 -webkit-transform 时固定位置不起作用

html - 表格属性宽度被忽略

html - CSS 问题 : IE 6+ not display 'cursor' correctly - ninja help needed

javascript - 如何对三个不同的变量使用相同的函数?

javascript - 在 parseFloat() 之后将对象键数组中的所有值相加

css - 如何创建网格/平铺 View ?

javascript - Google 脚本 HTML/CSS/JS 代码未运行