如何使用Javascript将一个列表项移动到无序列表中的指定索引(位置)。

问题描述 投票:2回答:4

假设我有一个下面的无序列表,如何将 "三 "移动到列表中的任何索引(位置)?这个方法应该是动态的。替换一个元素的文本内容是不行的。因为每一个列表项中也会包含其他元素。

<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>
  .
  .
  .
  <li>Hundred</li>  /* Nth List Element */
</ul>

尝试了已经回答过类似问题的解决方案。但是没有得到想要的结果。

我已经尝试过这个方法

  1. 通过jQuery获取数组中的列表。
  2. 使用array.each遍历数组
  3. 然后用prepend将特定的li移到列表的顶部

但通过这种方法,我只能将li元素移动到列表的顶部。而不是在任何想要的位置。

javascript html jquery css html-lists
4个回答
1
投票

我会用基于索引的方法的构造函数来解决这个问题。

function LiMover(liParent){
  this.kids = liParent.children;
  this.move = (index, beforeIndex = null)=>{
    const k = this.kids, e = k[index];
    if(beforeIndex === null){
      liParent.appendChild(e)
    }
    else{
      liParent.insertBefore(e, k[beforeIndex]);
    }
    return this;
  }
}
const liMover = new LiMover(document.querySelector('ul'));
liMover.move(0); // move 0 index (one) after last index
liMover.move(5, 0); // move 5 index (one) back to 0 index
liMover.move(1, 4); // move 1 index (two) to 4 index
liMover.move(3, 5).move(2, 0); // showing return this chain
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>  
</ul>

1
投票

const ul = document.querySelector('ul');
const items = [...ul.querySelectorAll('li')];

const moveItem = (from, to) => {
  if (to > items.length - 1 || to < 0) return;
  
  const item = items[from];
  if (!item) return;
  
  ul.removeChild(item);
  ul.insertBefore(item, ul.children[to]);
}

moveItem(5, 0);
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
  <li>four</li>
  <li>five</li>
  <li>six</li>  
</ul>

0
投票

这当然是可以解决的 我已经实现了一个函数,它可以交换一个集合的两个项目。

function swap(items, first, second) {
    var aux = items[first].innerHTML;
    items[first].innerHTML = items[second].innerHTML;
    items[second].innerHTML = aux;
}

swap(document.querySelectorAll("ul > li"), 2, 4);

请看这里的fiddle: https:/jsfiddle.net5qropsvu


0
投票

试一试

  const listElts = Array.from(document.querySelectorAll('li'));
  const swap1 = listElts[2].textContent;
  const swap2 = listElts[4].textContent;
  listElts[2].textContent = swap2;
  listElts[4].textContent = swap1;
© www.soinside.com 2019 - 2024. All rights reserved.