Javascript - Codepen 试图使用数组更改我的 html 内容的顺序,我的函数正在工作,但不是很好,我不明白为什么



https://codepen.io/thibault-cabanes/pen/xmvYqr

嗨!如果有人可以帮助我,我不知道是我的代码逻辑错了还是我犯了一些错误,所以请看一下!

我创建了一个名为"多米诺骨牌"的数组,其中包含 13 个条目;

我将多米诺骨牌的每个条目与我的 html 的每个div 类=多米诺骨牌与我的"留置权"函数链接;

我使用"洗牌"功能洗牌多米诺骨牌数组;

我在文档中发回我的div 的新顺序;

'

const reload = (array) => {
  let len = array.length-1 ;
  for (var i = 0; i <= len; i++) {
    let n = i+1,
    //
     par = document.getElementById('pioche'),
     son = array[i],
     old = document.getElementById("d"+n);
         par.replaceChild(son, old);
    //another way to do the same thing
    /*document.getElementById("pioche").replaceChild(array[i], 
    document.getElementById('d'+ n));*/ 
  }} 
lien(dominos);
shuffle(dominos);
reload(dominos)
console.log(dominos); `
在最后一次操作中,我丢失了一些 html 多米诺骨牌,

而在操作结束时,我的数组已满且随机播放,我的一些 html 多米诺骨牌丢失了,当您刷新时,DOM 中缺少的多米诺骨牌数量不同......

首先,你的shuffle函数会创建一些随机数组,但不是源元素的随机数组。以下是您可以解决它的方法:

const shuffle = (array) => {
  let len = array.length - 1;
  let dominos = array.slice(0); //make a copy of your original array
   for  ( var i = len; i >= 0 ; i--){
        //select random index from 0 to array length
        var j = Math.floor(Math.random() * (dominos.length - 1));
        /*delete element at selected index from copy of the original array, 
        so it can't be randomly chosen again*/ 
        temp = dominos.splice(j, 1);
        //replace the element in the origin array with the randomly selected one
        array[i] = temp[0]; 
   }
}

第二个问题是使用 getElementById重新加载函数中选择元素。当您进行替换时,您有可能添加的元素与 DOM 树中已有的 id 相同。之后,您的 id 不再是唯一的,并且根据文档:id 属性为 HTML 元素指定唯一 ID(该值在 HTML 文档中必须是唯一的)。由于 id 不是唯一的,getElementById 的行为是不可预测的。但是你总是可以从父元素用子节点来称呼子节点,这就是你可以修复它的方法:

const reload = (array) => {
  let len = array.length-1 ;
  for (var i = 0; i <= len; i++) {
    let n = i+1,
     par = document.getElementById('pioche'),
     son = array[i],
     //old = document.getElementById("d"+n); this line makes it all wrong
     old = par.childNodes[i]; //this way you are always addressing the correct child
     par.replaceChild(son, old);
  }} 
lien(dominos);
shuffle(dominos);
reload(dominos)
console.log(dominos);

现在它应该一切正常。

最新更新