javascript 在 < div>< li>页面加载时使用纯JS随机化s的顺序

xe55xuns  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(119)

我看到了使用jQuery随机化<div>(或<li> s或其他)顺序的多个答案,但我如何使用纯javascript做到这一点?

<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
</ul>
yyyllmsg

yyyllmsg1#

随机混洗克隆的li元素数组,并用新元素替换原始元素:
对于shuffleFisherYates函数see

function reOrderListItemsRandomly(ulId) {
  const ul = document.querySelector(`ul#${ulId}`);
  const liElems = ul.querySelectorAll(`li`);

  // create new array with cloned li elements and shuffle it
  const nwLiElems = shuffleFisherYates([...liElems]
    .map(li => li.cloneNode(true)));

  // replace the old li with the corresponding li from the 
  // array of new elements, see also
  // https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith
  [...liElems].forEach( (li, i) => li.replaceWith(nwLiElems[i]) );

  // see https://stackoverflow.com/a/49555388/58186
  function shuffleFisherYates(array) {
    let i = array.length;
    while (i--) {
      const ri = Math.floor(Math.random() * i);
      [array[i], array[ri]] = [array[ri], array[i]];
    }
    return array;
  }
}

// button handling
document.addEventListener(`click`, handle);

function handle(evt) {
  if (evt.target.id === `shuffle`) {
    return reOrderListItemsRandomly(`wrapper`);
  }
}
<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
  <li>Answer 4</li>
  <li>Answer 5</li>
  <li>Answer 6</li>
</ul>
<button id="shuffle">shuffle answers</button>
hm2xizp9

hm2xizp92#

这里我的解决方案:

<ul id="wrapper">
  <li>Answer 1</li>
  <li>Answer 2</li>
  <li>Answer 3</li>
  <li>Answer 4</li>
  <li>Answer 5</li>
  <li>Answer 6</li>
</ul>
<script>
(function() {
  const wrapper = document.getElementById("wrapper")
  const children = Array.from(wrapper.children)

  for(i = children.length - 1; i > 0; i--) {
    const ri = Math.floor(Math.random() * (i + 1));
    [children[ri], children[i]] = [children[i], children[ri]]
  }
  children.forEach(node => wrapper.appendChild(node))
})()
</script>

首先,它获取 Package 器的子元素,并使用Array.from将它们转换为一个Array;然后,它使用Fisher-Yates shuffle algorithm对该数组进行混洗;最后,我们对该数组调用forEach,并按照混洗后的数组的顺序将每个<li>再次添加到 Package 器中(添加元素会将其从先前的位置移除)。

相关问题