Home > Back-end >  Add a number for each data-toggle="modal" and data-target="exampleModal" in a ge
Add a number for each data-toggle="modal" and data-target="exampleModal" in a ge

Time:08-11

I have some mapped json data to display the results in a container. Each list from the generated html must open a separate modal window. To do this, I need to associate a number to each data-toggle="modal" and to each data-target="exampleModal" in the generated code.

I tried to add in data-modal="modal${res[i]} but I don't get a number this way.

The generated code:

const res = some.d.results; //arr of objects
let ul = document.querySelector('#test');
            const html = res.map(el=> {
                for (i = 1; i < res.length; i  ) {
                    return `<li  type="button" data-toggle="modal${res[i]}" data-target="exampleModal${res[i]}">
                                <a  href="#">
                                    <div >
                                        <img  alt="" src="${res.dirRef}${'/'}${res.fileRef}" />
                                    </div>
                                        <h2 >${res.PersonA.Person}</h2>
                                        <h3 >${res.Title}</h3>
                                </a>
                            </li>
                            <div  id="exampleModal${res[i]}" tabindex="-1">
                                <div >
                                    <div >
                                        <div >
                                            <p>${res.DescA.PersA]}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>`;
                }
            }).join("");

What is the proper way to add a number here?

CodePudding user response:

You seem to be looping over res multiple times, once with map() and once with for(...). But then your for-loop is returning on the first iteration and therefore not reaching subsequent iterations. You can include an index in your map(): res.map((el,i) => {...} and then use that instance of i, rather than a separate for-loop.

  • Related