给元素添加子节点,元素子节点数改变,反过来影响上方调用其值的异步任务、回调函数(如click。load,定时器等

var ulimg = document.querySelector('.img');
var ulspot = document.querySelector('.spot');
var imglis = ulimg.querySelectorAll('li');
var left = document.querySelector('.left');
var right = document.querySelector('.right');

//ulimg子节点数为4;

for (var i = 0; i < ulimg.children.length; i++) {
    // 创建一个小li
    var lis = document.createElement('li');
    // lis.innerHtml = '<a href="javascript:;">1</a>';
    // 把小li插入ulspot
    ulspot.appendChild(lis);
}


//ulimg子节点数为4;


// 把第一个小li的类名设置为current
ulspot.children[0].className = 'current';


// 点击小圆点变色
for (var i = 0; i < ulimg.children.length; i++) {
    ulspot.children[i].setAttribute('index', i);
    //ulimg子节点数为4;

    ulspot.children[i].onclick = function () {

        //ulimg子节点数在onclick 回调函数中为5;

        // 清除所有颜色 排他思想 
        for (var i = 0; i < ulimg.children.length - 1; i++) {
            ulspot.children[i].style.backgroundColor = 'white';
        }

        //现在的 ulimg.children.length=5;因为是onclick是回调函数
        // 在进行onclick之后才会执行,在这之前会先把所有的同步任务执行完
        // 以至于即使在某个回调函数下方修改这个回调函数会用到的值
        // 也会影响到回调函数的执行,同步任务中最后修改的值为准,和
        // 代码执行顺序无关,和事件执行顺序有关,回调函数在同步任务之后执行
        // 所以即使是在ulimg.children.length从4到5的
        // 代码的上方,但是由于先执行同步任务,所以也会反过来
        // 影响到onclick这个异步任务里的值。
        // 所以用i < ulimg.children.length - 1;

        this.style.backgroundColor = 'red';
        // 点击小圆圈,移动图片,移动ul
        // ul移动的距离即为小圆圈li索引号乘图片宽度

        var x = this.getAttribute('index');
        animate(ulimg, -imglis[0].offsetWidth * x);

        //ulimg子节点数为5(回调函数click中);
    }

    //ulimg子节点数为4;


}


// 添加克隆节点first,给ulimg作为子节点,添加后ulimg的子节点数为5,之前为4;
//ulimg子节点数开始为4;
var first = ulimg.children[0].cloneNode(true);
ulimg.appendChild(first);
//ulimg子节点数开始为5;
原文地址:https://www.cnblogs.com/xjt31/p/13062977.html