按字母顺序对页面上的元素进行排序

用户名

我正在尝试在按钮单击页面上对div的文本内容进行排序。

JS小提琴链接:https : //jsfiddle.net/Jamescodes/4k7xonqv/188/

的HTML

  <button id="myBtn">
    Sort Em!
  </button>

  <div class="red sortme">Steve</div>
  <div class="orange sortme">Dex</div>
  <div class="yellow sortme">Bob</div>
  <div style="color: green;" class="sortme">Colin</div>
  <div class="cyan sortme">James</div>
  <div class="blue sortme">Margie</div>
  <div class="purple sortme">Albert</div>

的CSS

.red {
  color: red;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}

.cyan {
  color: cyan;
}

.blue {
  color: blue;
}

.purple {
  color: purple;
}

div.sortme {
  text-align: center;
  padding: 2px;
  max-width: 5rem;
  background-color: hsl(0, 0%, 0%, 0.85);
  border-radius: 5px;
}

button {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
}

的JavaScript

function sortThem(s) {
  console.log('sorting');
  Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort(ea, eb) {
    var a = ea.textContent.trim();
    var b = eb.textContent.trim();
    console.log(a, b);
    if (a.textContent < b.textContent) return -1;
    if (a.textContent > b.textContent) return 1;
    return 0;
  }).forEach(function(div) {
    div.parentElement.appendChild(div);
  });
}
// call it like this
document.getElementById("myBtn").addEventListener("click", function() {
  sortThem('div.sortme')
});

div没有按我期望的那样排序,当我在单击时调用函数时。有人可以帮助我理解为什么吗?

西尔

也许将其放在这样的父容器中更安全,并简化您的代码。

const sortThem = (parentId, selector) => {
  const parent = document.getElementById(parentId);
    const divs = [...parent.querySelectorAll(selector)];
  divs.forEach(div => div.remove());
  divs.sort((a, b) => (a.innerText > b.innerText) ? 1 : -1);
  divs.forEach(div => parent.append(div));
}

document.getElementById("myBtn").addEventListener("click", function() {
  sortThem('parent', 'div.sortme')
});
.red {
  color: red;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}

.cyan {
  color: cyan;
}

.blue {
  color: blue;
}

.purple {
  color: purple;
}

div.sortme {
  text-align: center;
  padding: 2px;
  max-width: 5rem;
  background-color: hsl(0, 0%, 0%, 0.85);
  border-radius: 5px;
}

button {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
}
 <button id="myBtn">
   Sort Em!
 </button>
 <div id="parent">
   <div class="red sortme">Steve</div>
   <div class="orange sortme">Dex</div>
   <div class="yellow sortme">Bob</div>
   <div style="color: green;" class="sortme">Colin</div>
   <div class="cyan sortme">James</div>
   <div class="blue sortme">Margie</div>
   <div class="purple sortme">Albert</div>
 </div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章