简体   繁体   English

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

[英]JavaScript ignores appendChild in 2nd and 4th loop

Here's the fiddle that successfully does what I am trying to do: http://jsfiddle.net/WoofurrBro/qcf4qcm6/2/ 这是成功完成我正在尝试做的小提琴: http : //jsfiddle.net/WoofurrBro/qcf4qcm6/2/

And here is my setup that's not working. 这是我的设置不起作用。

 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> 

Before the code runs, the boxes start out in the order 11 22 33 44, and I want the script to dynamically create three columns and place them one at a time into whichever is the shortest column at each step. 在代码运行之前,方框以11 22 33 44的顺序开始,并且我希望脚本动态创建三列,并一次将它们放置在每一步中最短的列中。

However, only two of the boxes are placed into columns. 但是,只有两个盒子放在列中。 The 22 and 44 boxes are completely ignored and I don't know why. 22和44框被完全忽略了,我不知道为什么。

What can I do to get it to work correctly? 我该怎么做才能使其正常工作?

appendChild() isn't being ignored. appendChild()不会被忽略。 It's being repeatedly used on the same element. 它被重复用于同一元素。

If you look in the bottom corner of the 11 box, you will see: 如果您查看11框的底角,则会看到:

0h2h3h

Your i + "h" text is getting added to the same box 3 times, which means that boxes[i] refers to the same box during 3 iterations of the loop. 您的i + "h"文本将被添加到同一框3次,这意味着boxes[i]在循环的3次迭代期间引用了同一框

How can this be? 怎么会这样? The issue here is that boxes is not an array. 这里的问题是boxes不是数组。 It's an HTMLCollection , and the order of its contents reflects the order of elements in the DOM at the current moment: 这是一个HTMLCollection ,其内容顺序反映了当前DOM中元素的顺序:

An HTMLCollection in the HTML DOM is live; HTML DOM中的HTMLCollection是实时的; it is automatically updated when the underlying document is changed. 当基础文档更改时,它会自动更新。

Source 资源

So this is what's happening: 所以这是正在发生的事情:

Your boxes start out in the order: 您的盒子按顺序开始:

[original boxes] 11 22 33 44   [columns]

So on the first iteration, boxes[i] is the 11 box and it's added to the first column. 因此,在第一次迭代中, boxes[i]是11个box,并将其添加到第一列。 Now the order is: 现在的顺序是:

[original boxes] 22 33 44      [columns] 11

On the next iteration, boxes[i] (aka boxes[1] ) is the 33 box and it's added to the second column, and the order is: 在下一次迭代中, boxes[i] (又名boxes[1] )是33个盒子,并将其添加到第二列,其顺序为:

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

On the next iteration boxes[i] (= boxes[2] ) is the 11 box again , and it's appended to the third column. 在下一次迭代中, boxes[i] (= boxes[2]再次是11 box,并将其附加到第三列。 The order is now: 现在的订单是:

[original boxes] 22 44         [columns] 33 11

On the last iteration, boxes[i] is the 11 box yet again, and it's appended to the first column: 在最后一次迭代中, boxes[i]仍然是11个盒子,并将其追加到第一列:

[original boxes] 22 44         [columns] 11 33

And that's the end of the story. 到此为止。


The reason why your jsfiddle works and your tumblr page doesn't is that in your tumblr page, the destination container is after the boxes' starting location, but in the jsfiddle, the container is before the boxes, so the unmoved boxes keep their ordinal positions the whole time. 为什么你的jsfiddle的作品和你的tumblr页没有的原因是,在你的tumblr页,目标容器是盒子起始位置 ,但在的jsfiddle,容器是盒子之前 ,所以不为所动箱保持其序一直定位。

Here is what your jsfiddle does if the container is moved to be after the boxes: 如果将容器移动到盒子后面,这就是您的jsfiddle所做的事情:

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


The fix for this is simple. 解决方法很简单。 Just convert boxes into an array before you start using it: 只需将boxes转换为数组,然后再开始使用它:

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

Do that, and everything should work alright. 这样做,一切都会正常进行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在js Fullcalender中找到第2个和第4个星期六? - How to find 2nd and 4th Saturday in js Fullcalender? 找出for循环javascript中的第四个数字? - finding out the 4th number in a for loop javascript? 如何使用while(!feof)仅选择一行的第2个和第4个值? - How to pick only every 2nd and 4th value of a line using while(!feof)? 我的滑块仅显示第1和第3个滑块,但不显示表格的第2和第4个滑块 - My slider only shows 1st and 3rd slider but not the 2nd and 4th slider for table 如何在 Kendodatepicker 中禁用除第 2 周和第 4 周星期四外的所有日期 - How to disable all days in month except 2nd and 4th week's Thursday in Kendodatepicker 如何使用css或jquery隐藏第2和第4行表? - How to hide the 2nd and 4th table row using css or jquery? 如果array包含2个相同的对象,则将第二个(或第3个,第4个)对象的值突变 - If array includes 2 objects which are the same, then mutate the 2nd (or 3rd, 4th) object's values 如何使用java脚本或jquery跳过2个日期之间的第2个和第4个星期六 - How to skip 2nd and 4th Saturday between 2 dates using java script or jquery jQuery如何获取第二和第三TD内容取决于第四点击 - JQuery how to fetch 2nd and 3rd TD content depend on 4th td click Javascript循环-第二个变量不显示 - Javascript Loop - 2nd variable Not Displaying
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM