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:

  1. you have return in wron gplace, loop ending after 1 iteration.

  2. you're overwriting newconel on each loop.

  3. you're overwriting newconel within loop (you have 2 lines both doing newconel =, 1 right after another).

  4. you're doing opening , closing div tag on each iteration, whereas question shows desired result has 1 div around whole thing.

  5. you're grabbing old html of conel repeatedly in loop; don't see reason grab old html at all.

  6. you can't have li direct child of div, , there no lis in listed desired result, you're including li 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

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -