【问题标题】:Re-order li elements with JavaScript使用 JavaScript 重新排序 li 元素
【发布时间】:2015-06-18 12:49:22
【问题描述】:

我有一个按字母顺序显示位置的 li,我想抓取列表的元素并以不同的顺序返回。

    <li class="single-contact-location">
      <span>Location</span> 
     ALocation, BLocation, CLocation, DLocation, ELocation, FLocation
    </li>   

比方说 BLocation、ALocation、CLocation、DLocation、ELocation、FLocation

var li = document.getElementsByClassName("single-contact-location")[0];

我得到了 li 类和带有位置的 span,但 span 让我感到困惑,因为我无法抓取和重新排序元素。

【问题讨论】:

  • 您可以将字符串拆分为一个空格并将其重新排序为一个数组吗?

标签: javascript html css list


【解决方案1】:

您可以使用以下代码读取位置列表:

/* querySelector: IE8+ support */
var span = document.querySelector(".single-contact-location > span");

/* get the next node after the span */
var textNodeAfterSpan = span.nextSibling;

/* Get the content of the text node and split it */
var locationList = textNodeAfterSpan.nodeValue.split(', ');

/* Reorder it */
var mainLocation = locationList[1];
locationList[1] = locationList[0];
locationList[0] = mainLocation;

/* Rewrite it */
textNodeAfterSpan.nodeValue = ' ' + locationList.join(', ');
<li class="single-contact-location">
  <span>Location</span> 
  ALocation, BLocation, CLocation, DLocation, ELocation, FLocation
</li>

【讨论】:

  • 谢谢 tzi 的回复,但是我怎样才能先显示 BLocation 再显示 ALocation 呢?这是一个非常好的答案,但随机重新排序。
  • 你只想拥有第二个?
  • 是的,或者首先是第三个。
【解决方案2】:

您可以使用childNode 属性来获取这些字段并进行相应的修改。这是一个小提琴http://jsfiddle.net/sdvowy38/1/

 var li = document.getElementsByClassName("single-contact-location");
 var arr=li[0].childNodes[2].textContent.trim().split(',');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多