【问题标题】:javascript appendChild multiple elements [duplicate]javascript appendChild多个元素[重复]
【发布时间】:2018-03-27 19:49:41
【问题描述】:

我对@9​​87654321@ 有疑问。在下面的代码中,我试图通过循环向 div 添加多个按钮元素,但我只得到一个按钮。我知道appendChild 的工作原理。在developers.mozilla 中说,如果元素已经存在,它将从其父元素中删除并重新设置。所以这就是我不能向节点添加多个相同元素(按钮)的原因。

所以这是我的问题,实现它的最佳和最佳方法是什么?

function Slide() {
    this.currentStep = 0;
    this.time = 2000;
    this.images = [];

    this.images[0] = 'images/image1.jpg';
    this.images[1] = 'images/image2.jpg';
    this.images[2] = 'images/image3.jpg';
    this.images[3] = 'images/image4.jpg';
    this.images[4] = 'images/image5.jpg';

    let imagesCount = this.images.length;
    let indicatorContainer = document.createElement('div');
        indicatorContainer.classList.add('slide-indicator');
    let buttonIndicator = document.createElement('button');
        buttonIndicator.classList.add('button-indicator');
        buttonIndicator.setAttribute('type', 'button');

    for (let i = 0; i < imagesCount; i+=1) {
        indicatorContainer.appendChild(buttonIndicator);
    }

    document.querySelector('.slide').appendChild(indicatorContainer);
}

Slide.prototype.carousel = function() {     // arrow function-ov chi ashxatum ...uxxel
    document.querySelector('.image').src = this.images[this.currentStep];

    this.currentStep < this.images.length - 1 ? this.currentStep += 1 : this.currentStep = 0;

    setTimeout(this.carousel.bind(imageSlide), this.time);
};



const imageSlide = new Slide();
imageSlide.carousel();
    <div class="wrapper">
        <div class="slide">
            <img class="image" src="" width="1000" height="500" alt="image">
        </div>
        <div class="controls">
            <button class="button prev" type="button">
                previous
                <span class="arrow arrow-prev"></span>
            </button>
            <button class="button next" type="button">
                next
                <span class="arrow arrow-next"></span>
            </button>
        </div>
    </div>

【问题讨论】:

  • 这是因为您在循环中附加了相同的buttonIndicator。为了让它工作,你应该在每次循环迭代中创建新元素
  • 在循环内移动let buttonIndicator和相关代码。

标签: javascript


【解决方案1】:

在您的方法中,您在每次循环迭代中分配相同的buttonIndicator,而不是创建任何新的。您需要做的是在每次循环迭代中创建新按钮,以使其按您想要的方式工作。

所以这应该有效:

    for (let i = 0; i < imagesCount; i+=1) {
        let buttonIndicator = document.createElement('button');
        buttonIndicator.classList.add('button-indicator');
        buttonIndicator.setAttribute('type', 'button');
        indicatorContainer.appendChild(buttonIndicator);
    }

此外,使用 const 而不是 let 更有意义,因为您不会重新分配这些变量。

【讨论】:

    【解决方案2】:

    使用cloneNode:

    indicatorContainer.appendChild(buttonIndicator.cloneNode());
    

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 2018-11-13
      相关资源
      最近更新 更多