I am using a Bootstrap Carousel, but the slides of the carousel are generated through DOM
by looping through an array called "Capris".
There is a button that displays on each slide that is also specific to each index.
What I am trying to do is when a User clicks on one of the buttons, it redirects them to a different HTML file and prints to DOM
that same index, just on the other HTML page.
I managed to do everything except having that index print to DOM
on the second HTML file. Here is a snippet of my code for the carousel and the button's event listener:
const buyCapriBttn = () => {
for (let i = 0; i < capris.length; i++) {
document.querySelector(`#${capris[i].name}`).addEventListener('click', function () {generateProduct(capris[i])});
}
}
const capriCarousel = () => {
let domString = '';
for (let i = 0; i < capris.length; i++) {
if (i === 0) {
domString += `
<div class="carousel-item active">
<img class="d-block w-100" src="${capris[i].imageUrl}" alt="Capri 1">
<div class="d-flex justify-content-center">
<a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html" role="button">Buy ${capris[i].name}</a>
</div>
<p class="capri-description">${capris[i].description}</p>
</div>
`;
} else if (i >= 1) {
domString += `
<div class="carousel-item">
<img class="d-block w-100" src="${capris[i].imageUrl}" alt="Capri 1">
<div class="d-flex justify-content-center">
<a id="${capris[i].name}" class="btn btn-primary capri-btn" href="/capris.html" role="button">Buy ${capris[i].name}</a>
</div>
<p class="capri-description">${capris[i].description}</p>
</div>
`;
} else;
}
printToDom("#carousel-items", domString);
buyCapriBttn();
}
When the button is clicked, it runs the generateProduct
function for that index. Here is a snippet of that function that is run:
const generateProduct = (selectedPants) => {
domString = '';
console.log(selectedPants);
for (let i = 0; i < capris.length; i++) {
if (capris[i] === selectedPants) {
domString += `
<div id="caprisDom">
<img id="buycaprispic" src="${capris[i].imageUrl}">
<div id="nameandrating">
<h5 id="buycaprisname">${capris[i].name}</h5><h2>☆☆☆☆☆</h2>
</div>
<div class="caprisinfobox">
<p id="caprisinfo">${capris[i].description}</p>
<div class="sizeandprice">
<div id="sizeselector">
<label id="sizelabel">Size:</label>
<select name="sizelist" id="size">
</select>
</div>
<h3 id="price">$${capris[i].price}</h3>
</div>
<button id="cartbutton">Add to Cart</button>
</div>
</div>
`;
}
}
printToDom('#caprismain', domString);
}
I have a printToDom
function that prints to those ids if you need that as well.
注意:在本练习中,我尝试不使用JQuery
任何想法和帮助都非常感谢!