JavaScript - extremely confused on removing elements from Container

后端 未结 4 1276
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 05:47

I\'m making a 2D, top-down Zelda style web rpg single player in JavaScript.

When the player (purple shirt) walks near a cat, it will \"rescue\" it... which basically rem

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-25 06:15

    I am not entirely sure whatever if this is the case (I can't know it without taking a look at your whole program), but it could be this:

    I assume that your "ContainerOfAnimals" is a HTML element and that you are retrieving it's child nodes using it's .children -property. The thing is that .children -property returns a "live list"!

    Let me demonstrate:

    var children = ContainerOfAnimals.children;
    console.log(children.length) // 2;
    
    ContainerOfAnimals.removeChild(children[0]);
    console.log(children.length) // 1;
    

    Let's say that you remove the very first child of ContainerOfAnimals. What happens? The children -list has now changed so that the second element becomes the first element, third element becomes the second element etc...

    You could fix this by using a static array containing all the children and like this:

    var children = [].slice.call(ContainerOfAnimals.children);
    console.log(children.length) // 2;
    
    ContainerOfAnimals.removeChild(children[0]);
    console.log(children.length) // 2;
    

    Now removing the element from the DOM -tree does not remove the element from the children array (which is static). Remember, that [].slice.call does not work in IE8 or lower.

    Let me know if this was the problem. I have not enough points to comment, so I had to make a full post :)

提交回复
热议问题