Vengo con un problema, espero me puedan ayudar a solucionar. Ya he buscado bastante en este lado, pero no pude encontrar una respuesta que resuelva mi problema. Recientemente trabajé con bucles sobre objetos con jquery cada uno y funcionó bien. Cajero automático Necesito recorrer las entradas de una matriz.
Este es un ejemplo de cómo se ve la matriz. Contiene matrices, que a su vez contienen el src de un img y el título del img.
var imgRef = [[http://127.0.0.1:5555/images/imgf0002.png, fig number 1],[http://127.0.0.1:5555/images/imgf0012.png, fig number 12]]Lo que me gustaría hacer es recorrer las matrices y crear un div para cada entrada. Dentro de los divs debe haber un img que contenga el src de la otra matriz y la etiqueta ap con el nombre. Luego, esto se agregará a otro elemento en el sitio web.
<div> <img src="http://127.0.0.1:5555/images/imgf0002.png"> <p>Fig number 1</p> </div> <div> <img src="http://127.0.0.1:5555/images/imgf0012.png"> <p>Fig number 2</p> </div>He comenzado con esto. Solo para ver si puedo recorrer las entradas, pero no funcionó.
$.each(imgRef, function (index, value) { $('<div />', { 'text': value }).appendTo('#localImg'); }); var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']] $.each(imgRef, function(index, value){ $('.localImg').append('<div><img src="'+value[0]+'"><p>'+value[1]+'</p></div>'); });tienes que iterar sobre la matriz con arr.forEach((elem) => {}) u otros métodos de iteración. Dado que cada uno de los elementos de la matriz principal es una matriz de dos elementos, puede usar la desestructuración de la matriz y usar [url, title] en lugar de elem en la función iteradora. Luego, en el cuerpo, cree la cadena html desde el título y la URL y agréguela a su objetivo usando el método $.append .
let theArray = [["url1","title1"],["url2","title2"] /*,...*/]; theArray.forEach(([url, title]) => { $('#localImg').append(`<div> <img src="${url}"> <p>${title}</p> </div>`); }); var imgRef = [['http://127.0.0.1:5555/images/imgf0002.png', 'fig number 1'],['http://127.0.0.1:5555/images/imgf0012.png', 'fig number 12']] $.each(imgRef, function (index, [src, text]) { // create the div element const div = $("<div></div>") // create the image and add src for it. const img = $('<img />', { src, }); // create the p element and add the text to it. const p = $('<p></p>', { text }) // append both image and p in the div div.append([img, p]) // then insert the block inside the localImage container. $('#localImg').append(div) }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="localImg"></div>