JavaScript 在第二次和第四次循环中忽略appendChild

标签 javascript dom appendchild

这是成功完成我想做的事情的 fiddle : http://jsfiddle.net/WoofurrBro/qcf4qcm6/2/

这是我的设置不起作用。

function align() {
    var x = document.getElementById('container').offsetWidth;
    var y = document.getElementsByClassName('box')[0].offsetWidth;
    var z = Math.floor(x / y);
    // finds # of columns

    for (var i = 0; i < z; i++) {
        document.getElementById('container').innerHTML += '<div class=col style="width:' + y + 'px;float:left;"></div>';
    };
    // creates columns

    var columns = document.getElementsByClassName('col');
    var boxes = document.getElementsByClassName('box');
    // variables for later use
    ///////////////////////////////////////////////////////////////////////////////
    for (var i = 0; i < boxes.length; i++) {
        var minIndex;
        var column = [];
        // minIndex = shortest column, column[] to sort NodeList

        for (var iii = 0; iii < columns.length; iii++) {
            column[iii] = columns[iii].clientHeight;
        };
        // converts columns[] (NodeList) to column[] (Array)

        column.sort(function (a, b) {
            return a - b;
        });
        // sorts the column[] array

        for (var ii = 0; ii < columns.length; ii++) {
            if (column[0] == columns[ii].clientHeight) {
                minIndex = ii;
                break;
            };
        };
        // picks the first item in the column[] array (shortest) and finds the index of it in columns[] NodeList

        boxes[i].style.visibility = 'visible';
        //ALSO, placing this under the appendChild string causes weird bugs (?)
        boxes[i].innerHTML += i + 'h';
        columns[minIndex].appendChild(boxes[i]); // !!!!!!!!!!!!!! SEEMS TO IGNORE THIS appendChild
        //places them and adds identification
    };
    ///////////////////////////////////////////////////////////////////////////////
};

window.onload = align;
 * {
     -webkit-touch-callout: none;
     -webkit-user-select: none;
     -khtml-user-select: none;
     -moz-user-select: none;
     -ms-user-select: none;
     user-select: none;
     cursor:default;
     margin:0px;
     padding:0px;
 }
 html {
     background-color:#20293F;
 }
 #title {
     text-align:center;
     padding-top:40px;
     font-size:60px;
     margin-bottom:10px;
 }
 #description {
     font-size:14px;
     text-align:center;
     margin:0 auto 30px auto;
     max-width:450px;
 }
 .box {
     width:250px;
     word-wrap:break-word;
     background-color:rgba(0, 0, 0, 0.30);
     margin:10px 0 10px 0;
 }
 col {
     margin:0 10px 0 10px;
 }
 #containerwrap {
     background-color:rgba(0, 0, 0, 0.30);
     min-width:800px;
     width:100%;
 }
 #container {
     overflow:hidden;
     width:800px;
     margin:0 auto;
 }
 .postTitle {
     text-align:center;
     font-size:30px;
     color:#5F70A6;
 }
 .postBody {
     padding:10px;
     font-size:12px;
     color:#5F70A6;
 }
<div id="containerwrap">
    <div id="container">
        <div class="box">
             <h2 class="postTitle">11 boots</h2>

            <div class="postBody">
                <p>11 bbooots</p>
            </div>
        </div>
        <div class="box">
             <h2 class="postTitle"></h2>

            <div class="postBody">
                <p>22 sweg</p>
            </div>
        </div>
        <div class="box">
             <h2 class="postTitle"></h2>

            <div class="postBody">
                <p><span></span><span></span><span>33 thisisadivthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimetocopythisshitsorries<span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span><span>divthingwithoutanyspanssodontevenexpectthehtmltogeneratespanslikeitdidlasttimebitchtimeto</span></span>
                </p>
            </div>
        </div>
        <div class="box">
             <h2 class="postTitle">44 ether</h2>

            <div class="postBody">
                <p>44 infinite, silk-smooth darkness covers your eyes as you float in the skies
                    <br>lightning bolts of pleasure and happiness strike you, through your senses, as each rain drop pops silently on your skin
                    <br>the windy silence cloak guards your peace as you rest in the sky, floating upwards and feeling the rain drops pop and the air flowing around you with kind love, giving you calmness and calmness again
                    <br>this sea of magic around you might not be, but does it matter, if that’s what’s on your mind. you let it stay and you float, you float away, as you let it be
                    <br>and it strikes you that you are where your mind is and your mind is here, here in this magic place, as the raindrops pop lightning on your skin, you allow it to be, might you never leave, but if you ever left, might you come back to be here once more
                    <br>just close your eyes</p>
            </div>
        </div>
    </div>
</div>

在代码运行之前,这些框以 11 22 33 44 的顺序开始,我希望脚本动态创建三列,并一次将它们放入每一步中最短的列中。

但是,只有两个框被放入列中。 22 和 44 框被完全忽略,我不知道为什么。

我该怎么做才能让它正常工作?

最佳答案

appendChild() 不会被忽略。它在同一元素上重复使用。

如果您查看 11 框的底 Angular ,您将看到:

0h2h3h

您的 i + "h" 文本被添加到同一个框中 3 次,这意味着 boxes[i] 引用同一个框 在循环的 3 次迭代期间。

怎么会这样呢?这里的问题是 boxes 不是数组。它是一个 HTMLCollection,其内容的顺序反射(reflect)了当前 DOM 中元素的顺序:

An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed.

Source

所以这就是发生的事情:

您的盒子按以下顺序开始:

[original boxes] 11 22 33 44   [columns]

因此,在第一次迭代中,boxes[i] 是第 11 个框,它被添加到第一列。现在的顺序是:

[original boxes] 22 33 44      [columns] 11

在下一次迭代中,boxes[i](又名boxes[1])是第 33 个框,它被添加到第二列,顺序为:

[original boxes] 22 44 11      [columns] 11 33

在下一次迭代中,boxes[i] (= boxes[2]) 再次是第 11 个框,并将其附加到第三栏。现在订单是:

[original boxes] 22 44         [columns] 33 11

在最后一次迭代中,boxes[i] 再次是 11 框,并且它被附加到第一列:

[original boxes] 22 44         [columns] 11 33

故事到此结束。

<小时/> jsfiddle 可以工作而 tumblr 页面不能工作的原因是,在 tumblr 页面中,目标容器位于框的起始位置之后,但在 jsfiddle 中,容器位于之前 盒子,因此未移动的盒子始终保持其顺序位置。

如果容器移动到框后面,您的 jsfiddle 将执行以下操作:

http://jsfiddle.net/qcf4qcm6/3/

<小时/> 解决这个问题的方法很简单。只需在开始使用之前将 boxes 转换为数组即可:

var boxes = document.getElementsByClassName('box');
boxes = Array.prototype.slice.apply(boxes);

这样做,一切都会正常。

http://jsfiddle.net/myqakknr/2/

关于JavaScript 在第二次和第四次循环中忽略appendChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27842832/

相关文章:

javascript - libxmljs 的替代品

javascript - 如何动态使用html元素内的document.write

javascript - AppendChild TypeError 即使 Child 是 HTML

javascript - 从对象内部访问时变量变为 0

javascript - 初始化新 Controller 时调用范围 $destroy 事件

javascript - Node Mysql查询队列但从不执行

javascript - 如何使图像标题显示在滚动条上

javascript - javascript/node.js 中的 seek() 等价物?

javascript - getSelection() 有跨浏览器的解决方案吗?

javascript - 将Child dataURI图像附加到window.open在IE中失败