javascript - Multiple Iteration in for-loop using jQuery html() instead of document.write -
i have 3 set of arrays got looping , sorting json data. let's say, arr1, arr2, arr3. want output arrays combined html codes 5 times. far, have code:
var max=5; (var b = 0;b < max;b++) { var conel = $('#container'); var newconel = conel.html(); newconel = '<ul>'; var newprop = '<li><span><a href="'+arr1[b]+'">'+arr2[b]+'</a><span>'+arr3[b]+'</span></span></li>'; newconel += newprop + '</ul>'; return conel.html(newconel); }
however, outputs 1 result. result:
<div> <span> <a href="#link-to-result-1">result-1-title</a> <span>view-count-1</span> </span> </div>
while, want have 5 output. desired result is:
<div> <span> <a href="#link-to-result-1">result-1-title</a> <span>view-count-1</span> </span> <span> <a href="#link-to-result-2">result-2-title</a> <span>view-count-2</span> </span> <span> <a href="#link-to-result-3">result-3-title</a> <span>view-count-3</span> </span> <span>...</span> </div>
i got desired output (five outputs) when using document.write(newprop);. but, not want use document.write method.
there several issues there:
you have
return
in wron gplace, loop ending after 1 iteration.you're overwriting
newconel
on each loop.you're overwriting
newconel
within loop (you have 2 lines both doingnewconel =
, 1 right after another).you're doing opening , closing
div
tag on each iteration, whereas question shows desired result has 1div
around whole thing.you're grabbing old html of
conel
repeatedly in loop; don't see reason grab old html at all.you can't have
li
direct child ofdiv
, , there noli
s in listed desired result, you're includingli
entries in html.
if set newconel
"<div>"
start with, append (+=
), add final "</div>"
@ end , set on element (not retrieving current html), should you're expecting:
var max = 5; // <== sure arr1, arr2, , arr3 have @ least 5 entries? var newconel = '<div>'; (var b = 0; b < max; b++) { newconel += '<span><a href="'+arr1[b]+'">'+arr2[b]+'</a><span>'+arr3[b]+'</span></span>'; } newconel += '</div>'; return $("#container").html(newconel);
or if you're open using bit more modern; note assumes arr1
, arr2
, , arr3
same length , want of entries, not five:
return $("#container").html( "<div>" + arr1.reduce(function(html, entry, i) { return html + '<span><a href="' + entry + '">' + arr2[i] + '</a><span>' + arr3[i] + '</span></span>'; }, "") + "</div>" );
Comments
Post a Comment