Javascript - Codepen 尝试使用数组更改我的 html 内容的顺序我的函数正在运行但不太好我不明白为什么

标签 javascript html arrays

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

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

我创建了一个名为“dominos”的数组,其中包含 13 个条目;

我将 domino 的每个条目与我的 html 的每个 div class= domino 和我的“留置权”功能链接起来;

我用“洗牌”功能洗牌多米诺骨牌数组;

我发回文档中我的 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 中缺少的多米诺骨牌......

最佳答案

首先,您的所有随机播放函数都会生成一些随机数组,但不会随机排列原始元素数组。修复方法如下:

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 在您的reload 函数中选择元素。进行替换时,您可能会添加与 DOM 树中已有的 id 相同的元素。之后,您的 ID 不再是唯一的,并且根据文档:the id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document) .由于 ID 不是唯一的,getElementById 的行为是不可预测的。但是您始终可以使用父元素中的 childNodes 来处理子元素,这就是您可以修复它的方法:

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);

现在它应该一切正常。

关于Javascript - Codepen 尝试使用数组更改我的 html 内容的顺序我的函数正在运行但不太好我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54272158/

相关文章:

javascript - 通过名称检测窗口是否存在

javascript - 添加隐藏类型后复选框无法禁用

Javascript - 在多维数组中查找多个值

arrays - 使用静态范围最小查询维护的数组中单个更改的复杂性

php - 为什么我无法将 CSV 文件中的新项目添加到 PHP 中 while 循环内的数组中?

javascript - JQuery closest() + find() 树遍历

javascript - 带链接的表单提交

html - 为什么我无法打印 R Markdown 文档中的代码颜色?

html - 带有 Logo 的登录模式

html - 在 Opera/Chrome 浏览器中滚动时,粘性导航栏会在某一时刻闪烁(渲染错误?)