incorrect substitution of dynamic argument into function
I have a problem with my code
There is a code of cycle
var myslides = document.getElementById("slider-list"); for (let i = 0; i < arr.length; i++) { id[i] = arr[i].id; pathToStudents[i] = `img/${arr[i].avatar}`; fio[i] = arr[i].fio; let slidediv = document.createElement("li"); slidediv.className = "slider-element"; slidediv.innerHTML = `<img src="${pathToStudents[i]}" alt="${fio[i]}" onClick="OpenCase(${id[i]});">`; let sliderp = document.createElement("p"); sliderp.className = "pSlides"; sliderp.innerHTML = `<a href="" class="aSlides">${fio[i]}</a>`; myslides.appendChild(slidediv); slidediv.appendChild(sliderp); };
The Dom-elements, which creates are:
<li class="slider-element" style="opacity: 0;"><img src="img/x36.jpg" alt="Oblak Y.B." onclick="OpenCase(36);"><p class="pSlides"><a href="" class="aSlides">Oblak Y.B.</a></p></li> <li class="slider-element" style="opacity: 0;"><img src="img/anotertkach.jpg" alt="Tkach I.L." Onclick="OpenCase(37);"><p class="pSlides"><a href="" class="aSlides">Tkach I.L.</a></p></li>
…. etc.
Function OpenCase has the next form:
function OpenCase(id) { $.ajax({ type: "post", dataType: "json", url: "php/getter.php", data: { mode: "spec" }, success: function (spec) { $.ajax({ url: "php/getter.php", type: 'post', dataType: "json", data: { mode: "student", id: id }, success: function (result) { ...
Despite the fact that the DOM elements are created with different values of the argument of the function OpenCase, it always produces the same result with the last i = arr.length-1.
If you manually substitute the argument value for the foo function in the DOM element, then it works without problems.
With what it can be connected? Can anybody help?
I will be very grateful for your help!
arr = [{ id: 1, fio: 1, avatar: 'x' }, { id: 2, fio: 2, avatar: 'y' }] id = [] fio = [] pathToStudents = [] var myslides = document.getElementById("slider-list"); for (let i = 0; i < arr.length; i++) { id[i] = arr[i].id; pathToStudents[i] = `img/${arr[i].avatar}`; fio[i] = arr[i].fio; let slidediv = document.createElement("li"); slidediv.className = "slider-element"; slidediv.innerHTML = `<img src="${pathToStudents[i]}" alt="${fio[i]}" onClick="OpenCase(${id[i]});">`; let sliderp = document.createElement("p"); sliderp.className = "pSlides"; sliderp.innerHTML = `<a href="" class="aSlides">${fio[i]}</a>`; myslides.appendChild(slidediv); slidediv.appendChild(sliderp); }; function OpenCase(id) { $.ajax({ type: "post", dataType: "json", url: "https://jsonplaceholder.typicode.com/posts", data: { mode: "spec" }, success: function(spec) { console.log('succ') $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", type: 'post', dataType: "json", data: { mode: "student", id: id }, success: function(result) { console.log(result) } }) } }) }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="slider-list"></div>