使用 vanilla js 创建一个编号元素

Creating a numbered element with vanilla js

我正在使用 dom 创建一些 html 元素。确切地说是按钮。我是 javascript 的新手,所以任何建议都将不胜感激。

我为此使用的 js 基于 divs 的节点列表。我正在使用 for 循环创建基于节点列表中每个对象的按钮(每个 div 生成一个按钮)。

这是js:

let indInit = function(){
 for(i = 0; i < slides.length; i++){
  document.querySelector('.gallery-indicator-nav').innerHTML +=
  '<button class="gallery-indicator" onclick="currentSlide(1)></button>';
 }
};
indInit();

显然,我最终得到了

<div class="gallery-indicator-nav">
<button class="gallery-indicator" onclick="currentSlide(1)></button>
<button class="gallery-indicator" onclick="currentSlide(1)></button>
<button class="gallery-indicator" onclick="currentSlide(1)></button>
</div>

我希望我的按钮像这样生成:

<div class="gallery-indicator-nav">
<button class="gallery-indicator" onclick="currentSlide(1)></button>
<button class="gallery-indicator" onclick="currentSlide(2)></button>
<button class="gallery-indicator" onclick="currentSlide(3)></button>
</div>

我假设我需要使用某种排序或数学对象和连接,但对 google 的研究至少可以说是令人困惑。我认为必须有一个简单的解决方案 =)

如果您使用 innerHTML,您可以像对待任何其他字符串一样对待它,因此:

***.innerHTML = 'xxxxxxx' + i + 'xxxxxx';

可以使用;

也许您想尝试创建按钮元素并附加一个 EventListener:

btn = document.createElement(....);
btn.addEventListener( .... );

经过Terry Wu的建议:

for(i = 0; i < slides.length; i++){
 document.querySelector('.gallery-indicator-nav').innerHTML +=
 '<button class="gallery-indicator" onclick="currentSlide(' + i + ')"></button>';
}

我结束了这个。完美:

<div class="gallery-indicator-nav">
  <button class="gallery-indicator" onclick="currentSlide(0)"></button>
  <button class="gallery-indicator" onclick="currentSlide(1)"></button>
  <button class="gallery-indicator" onclick="currentSlide(2)"></button>
</div>