我正在使用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的研究令人困惑。我认为必须有一个简单的解决方案=)
答案 0 :(得分:0)
如果您使用的是innerHTML
,则可以将其与其他任何字符串一样对待,因此:
***.innerHTML = 'xxxxxxx' + i + 'xxxxxx';
可以使用;
也许您想尝试创建button元素并附加一个EventListener:
btn = document.createElement(....);
btn.addEventListener( .... );
答案 1 :(得分:0)
在特里·吴的建议下:
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>