I am using the dom to create some html elements. Button to be exact. I am pretty new to javascript so any advice would be appreciated.
The js I am using for this is based on a nodelist of divs. I am using a for loop to create buttons that are based on each object in the nodelist (each div spawns a button).
Here is the 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();
Obviously, I end up with
<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>
I would like my buttons to generate like this:
<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>
I am assuming I need to use some sort or math object and concatenation but research on google has been confusing to say the least. I figure there must be a simple solution =)
If you're using innerHTML
you can treat it like any other strings, so:
***.innerHTML = 'xxxxxxx' + i + 'xxxxxx';
can be used;
Maybe you want to try to create the button element and attach an EventListener:
btn = document.createElement(....);
btn.addEventListener( .... );
After Terry Wu's suggestion:
for(i = 0; i < slides.length; i++){ document.querySelector('.gallery-indicator-nav').innerHTML += '<button class="gallery-indicator" onclick="currentSlide(' + i + ')"></button>'; }
I ended up with this. Perfect:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.