我正在使用dom创建一些html元素。按钮准确。我对javascript很陌生,所以任何建议都将不胜感激。
我正在为此使用的js基于div的节点列表。我正在使用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';
可以使用;
也许您想尝试创建button元素并附加一个EventListener:
btn = document.createElement(....);
btn.addEventListener( .... );